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

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

Bun 的服务器端 `WebSocket` API 提供了原生的发布-订阅（pub-sub）API。你可以使用 `socket.subscribe(<name>)` 让套接字订阅一组命名频道；也可以使用 `socket.publish(<name>, <message>)` 向某个频道发布消息。

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

```ts server.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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}`);
```
