From 4c89c60867591b50e0b31bf5009fd5ad6a3cebe1 Mon Sep 17 00:00:00 2001 From: Colin McDonnell Date: Wed, 26 Jul 2023 14:59:39 -0700 Subject: Add files (#3826) --- docs/guides/websocket/pubsub.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 docs/guides/websocket/pubsub.md (limited to 'docs/guides/websocket/pubsub.md') diff --git a/docs/guides/websocket/pubsub.md b/docs/guides/websocket/pubsub.md new file mode 100644 index 000000000..7403d4d2f --- /dev/null +++ b/docs/guides/websocket/pubsub.md @@ -0,0 +1,38 @@ +--- +name: Build a publish-subscribe WebSocket server +--- + +Bun's server-side `WebSocket` API provides a native pub-sub API. Sockets can be subscribed to a set of named channels using `socket.subscribe()`; messages can be published to a channel using `socket.publish(, )`. + +This code snippet implements a simple single-channel chat server. + +```ts +const server = Bun.serve<{ username: string }>({ + fetch(req, server) { + const cookies = req.headers.get("cookie"); + const username = getUsernameFromCookies(cookies); + const success = server.upgrade(req, { data: { username } }); + if (success) return undefined; + + return new Response("Hello world"); + }, + websocket: { + open(ws) { + const msg = `${ws.data.username} has entered the chat`; + ws.subscribe("the-group-chat"); + ws.publish("the-group-chat", msg); + }, + message(ws, message) { + // the server re-broadcasts incoming messages to everyone + ws.publish("the-group-chat", `${ws.data.username}: ${message}`); + }, + close(ws) { + const msg = `${ws.data.username} has left the chat`; + ws.publish("the-group-chat", msg); + ws.unsubscribe("the-group-chat"); + }, + }, +}); + +console.log(`Listening on ${server.hostname}:${server.port}`); +``` -- cgit v1.2.3