Skip to content

Commit 52e787a

Browse files
committed
README
1 parent 6364c4c commit 52e787a

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

README.md

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,38 @@
1616

1717
**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).
1818

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+
```
2251

2352
Check the website for more info [https://distributedobjectprotocol.org/](https://distributedobjectprotocol.org/guide/javascript)
2453

0 commit comments

Comments
 (0)