Using dop with WebSockets
// Server
const { createNode } = require('dop')
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8080 })
const sum = (a, b) => a + b
const multiply = (a, b) => a * b
const getCalculator = () => ({ sum, multiply })
wss.on('connection', ws => {
const client = createNode()
client.open(ws.send.bind(ws), getCalculator)
ws.on('message', client.message)
})
// Client
const ws = new WebSocket('ws://localhost:8080')
const server = createNode()
ws.on('open', async () => {
const getCalculator = server.open(ws.send.bind(ws))
const { sum, multiply } = await getCalculator()
const result1 = await sum(5, 5) // <-- CHANGE THIS
const result2 = await multiply(3, 3) // <-- CHANGE THIS
console.log({ result1, result2 })
})
ws.on('message', server.message)
""
no comments