运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

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

Bun 服务端的 WebSocket API 内置原生发布-订阅功能。使用 socket.subscribe(<name>) 让套接字订阅一组命名频道;使用 server.publish(<name>, <message>) 向频道发布消息。

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

server.ts
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("你好,世界");
  },
  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}`);