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

# 构建发布-订阅 WebSocket 服务器

Bun 的服务端 `WebSocket` API 包含原生发布-订阅功能。使用 `socket.subscribe(<名称>)` 将套接字订阅到一组命名频道；使用 `socket.publish(<名称>, <消息>)` 向频道发布消息。

此代码片段实现了一个单频道聊天服务器。

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const server = Bun.serve({
  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: {
    // TypeScript：像这样指定 ws.data 的类型
    data: {} as { username: string },

    open(ws) {
      const msg = `${ws.data.username} 进入了聊天室`;
      ws.subscribe("the-group-chat");
      server.publish("the-group-chat", msg);
    },
    message(ws, message) {
      // 服务器将收到的消息重新广播给所有人
      server.publish("the-group-chat", `${ws.data.username}: ${message}`);
    },
    close(ws) {
      const msg = `${ws.data.username} 离开了聊天室`;
      server.publish("the-group-chat", msg);
      ws.unsubscribe("the-group-chat");
    },
  },
});

console.log(`监听于 ${server.hostname}:${server.port}`);
```
