Bun

指南WebSocket

使用 Bun 構建釋出/訂閱 WebSocket 伺服器

Bun 的伺服器端 WebSocket API 提供了原生的釋出/訂閱 API。可以使用 socket.subscribe(<name>) 將套接字訂閱到一組命名通道;可以使用 socket.publish(<name>, <message>) 將訊息釋出到通道。

此程式碼段實現了一個簡單的單通道聊天伺服器。

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: specify the type of ws.data like this
    data: {} as { username: string },

    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}`);