Bun

指南WebSocket

使用 Bun 构建发布-订阅 WebSocket 服务器

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

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

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");
      server.publish("the-group-chat", msg);
    },
    message(ws, message) {
      // the server re-broadcasts incoming messages to everyone
      server.publish("the-group-chat", `${ws.data.username}: ${message}`);
    },
    close(ws) {
      const msg = `${ws.data.username} has left the chat`;
      server.publish("the-group-chat", msg);
      ws.unsubscribe("the-group-chat");
    },
  },
});

console.log(`Listening on ${server.hostname}:${server.port}`);