> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/zhcndoc/bun/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a pub/sub WebSocket server

> Implement publish-subscribe pattern with WebSockets

Bun's WebSocket implementation includes built-in pub/sub support.

## Pub/Sub Server

```typescript server.ts theme={null}
Bun.serve({
  fetch(req, server) {
    server.upgrade(req);
  },
  websocket: {
    open(ws) {
      ws.subscribe("chat");
    },
    message(ws, message) {
      // Publish to all subscribers
      ws.publish("chat", message);
    },
  },
});
```

## Multiple Channels

```typescript theme={null}
Bun.serve({
  websocket: {
    open(ws) {
      ws.subscribe("lobby");
    },
    message(ws, message) {
      const data = JSON.parse(message);
      
      if (data.action === "join") {
        ws.subscribe(data.channel);
        ws.send(JSON.stringify({ joined: data.channel }));
      } else if (data.action === "send") {
        ws.publish(data.channel, data.message);
      }
    },
  },
});
```

See [WebSocket API](/api/websockets) for complete documentation.
