|
| 1 | +# joinRealtimeChannel (experimental) |
| 2 | + |
| 3 | +```js |
| 4 | +const realtimeChannel = window.webxdc.joinRealtimeChannel(); |
| 5 | +``` |
| 6 | + |
| 7 | +Setup and return the realtime channel for this app, |
| 8 | +with methods for listening and sending data as well as leaving the channel. |
| 9 | +Per-app realtime channels are: |
| 10 | + |
| 11 | +- **private**: no one outside the chat can participate in realtime channels. |
| 12 | + |
| 13 | +- **isolated**: apps can not participate in realtime channels of other apps. |
| 14 | + |
| 15 | +- **ephemeral**: any sent data will only be received by currently |
| 16 | + connected peers but not by peers connecting later. |
| 17 | + |
| 18 | +Calling `joinRealtimeChannel` a second time without leaving the prior one |
| 19 | +will throw an error. |
| 20 | + |
| 21 | +## `realtimeChannel.setListener((data) => {})` |
| 22 | + |
| 23 | +Start listening on the realtime channel using the specified callback. |
| 24 | +The callback receives `Uint8Array` data items that were sent from connected peers. |
| 25 | +Calling `setListener` a second time will replace the previous listener. |
| 26 | + |
| 27 | + |
| 28 | +## `realtimeChannel.send(data)` |
| 29 | + |
| 30 | +Send a `Uint8Array` data item to connected peers. |
| 31 | +There is no guarantee anyone is receiving sent data |
| 32 | +because there might be no currently listening peers, |
| 33 | +or network connections fail. |
| 34 | +It is up to the app to determine connectivity status with other peers |
| 35 | +by monitoring and triggering data messages. |
| 36 | + |
| 37 | + |
| 38 | +## `realtimeChannel.leave()` |
| 39 | + |
| 40 | +Leave the realtime channel. |
| 41 | +Afterwards the `realtimeChannel` is invalid and |
| 42 | +can not be used anymore for sending or receiving data. |
| 43 | +You need to call `window.webxdc.joinRealtimeChannel()` again |
| 44 | +to re-join the per-app realtime channel. |
| 45 | + |
| 46 | +## Example |
| 47 | + |
| 48 | +```js |
| 49 | +const realtimeChannel = window.webxdc.joinRealtimeChannel(); |
| 50 | +realtimeChannel.setListener((data) => { |
| 51 | + console.log("Received realtime data: ", data); |
| 52 | + const msg = new TextDecoder().decode(data); |
| 53 | + console.log("decoded message: ", msg); |
| 54 | +}) |
| 55 | + |
| 56 | +let numMsgs = 0 |
| 57 | +const refreshIntervalId = setInterval(() => { |
| 58 | + const myId = window.webxdc.selfAddr; |
| 59 | + const data = new TextEncoder().encode(`[${numMsgs}] hello from ${myId}`); |
| 60 | + numMsgs += 1 |
| 61 | + console.log("Sending message", data); |
| 62 | + realtimeChannel.send(data); |
| 63 | + if (numMsgs >= 100) { |
| 64 | + realtimeChannel.leave(); |
| 65 | + clearInterval(refreshIntervalId); |
| 66 | + } |
| 67 | + |
| 68 | +}, 1000) |
| 69 | +``` |
0 commit comments