|
16 | 16 |
|
17 | 17 | **Distributed Object Protocol** is a thin layer on top of your data network that helps you communicate server and clients (nodes) using [RPCs](https://en.wikipedia.org/wiki/Remote_procedure_call). It is also a pattern that makes easy update, mutate or even sync the state of your App using [Patches](https://github.com/DistributedObjectProtocol/protocol#Patches). |
18 | 18 |
|
19 | | -## RPCs with WebSockets |
20 | | - |
21 | | -image |
| 19 | +## Quick example using RPCs with WebSockets |
| 20 | + |
| 21 | +```js |
| 22 | +// Server |
| 23 | +const { createNode } = require('dop') |
| 24 | +const WebSocket = require('ws') |
| 25 | +const wss = new WebSocket.Server({ port: 8080 }) |
| 26 | + |
| 27 | +const sum = (a, b) => a + b |
| 28 | +const multiply = (a, b) => a * b |
| 29 | +const getCalculator = () => ({ sum, multiply }) |
| 30 | + |
| 31 | +wss.on('connection', ws => { |
| 32 | + const client = createNode() |
| 33 | + client.open(ws.send.bind(ws), getCalculator) |
| 34 | + ws.on('message', client.message) |
| 35 | +}) |
| 36 | +``` |
| 37 | + |
| 38 | +```js |
| 39 | +// Client |
| 40 | +const ws = new WebSocket('ws://localhost:8080') |
| 41 | +const server = createNode() |
| 42 | +ws.on('open', async () => { |
| 43 | + const getCalculator = server.open(ws.send.bind(ws)) |
| 44 | + const { sum, multiply } = await getCalculator() |
| 45 | + const result1 = await sum(5, 5) |
| 46 | + const result2 = await multiply(3, 3) |
| 47 | + console.log(result1, result2) // 10, 9 |
| 48 | +}) |
| 49 | +ws.on('message', server.message) |
| 50 | +``` |
22 | 51 |
|
23 | 52 | Check the website for more info [https://distributedobjectprotocol.org/](https://distributedobjectprotocol.org/guide/javascript) |
24 | 53 |
|
|
0 commit comments