|
2 | 2 |
|
3 | 3 | Bidirectional WebSocket RPC with a Durable Object audit log. |
4 | 4 |
|
5 | | -The server defines the same toy methods as `worker-basic`, but each call also |
6 | | -broadcasts an audit event to every connected client via `onEvent()` — a method |
7 | | -the _server_ calls on the _client_. Open the page in two browser tabs and watch |
8 | | -events from one tab appear in the other. |
| 5 | +We have a bidirectional RPC implementation, so we should use it, right? |
| 6 | + |
| 7 | +This demo has the server invoking remote methods on the client. Each call |
| 8 | +on the server emits an event to the client. |
| 9 | + |
| 10 | +It's worth calling out that you likely need some centralized state with this |
| 11 | +approach. A worker connected via a websocket could work in theory in that it |
| 12 | +can respond to requests coming in over the same connection. However if you have |
| 13 | +multiple sessions per user (think multiple tabs, or a desktop or mobile app) you |
| 14 | +likely want to send those requests to every session for a particular user. |
| 15 | + |
| 16 | +The best way to do that is a Durable Object. This demo app gives an example. Open |
| 17 | +the page in two browser tabs and watch events from one tab appear in the other. |
9 | 18 |
|
10 | 19 | ## Setting up a bi-directional WebSocket RPC session |
11 | 20 |
|
12 | | -The main difference between this example and `worker-basic` is that we're explicitly setting up a bi-directional WebSocket RPC session with `newWorkersWebSocketRpcSession`. This returns the upgrade |
13 | | -response and an `RpcSession` — use `session.remote` to call methods on the client, and |
14 | | -`session.onClose()` to clean up when the connection drops. |
| 21 | +The main difference between this example and `worker-basic` is that we're explicitly setting up a bi-directional WebSocket RPC session with `newWorkersWebSocketRpcSession`. This returns the upgrade response and an `RpcSession`. Use `session.remote` to call methods on the client, and `session.onClose()` to clean up when the connection drops. |
15 | 22 |
|
16 | 23 | ```ts |
17 | 24 | // Set up bidirectional RPC with the client |
@@ -48,7 +55,7 @@ Open http://localhost:8787. |
48 | 55 |
|
49 | 56 | ``` |
50 | 57 | src/worker.ts Worker + AuditLog Durable Object |
51 | | -web/src/app.ts Client — bidirectional RPC with onEvent handler |
| 58 | +web/src/app.ts Client - bidirectional RPC with onEvent handler |
52 | 59 | web/src/style.css Styles (two-column layout) |
53 | 60 | web/index.html Vite entry point |
54 | 61 | web/vite.config.ts Aliases @jmorrell/jsonrpc to the local dist build |
|
0 commit comments