Bun

指南WebSocket

使用 Bun 在 WebSocket 上设置每个套接字的上下文数据

在构建 WebSocket 服务器时,通常需要存储与每个已连接客户端关联的一些识别信息或上下文。

使用 Bun.serve(),在通过 server.upgrade() 调用中传递 data 参数来最初升级连接时设置此“上下文数据”。

Bun.serve<{ socketId: number }>({
  fetch(req, server) {
    const success = server.upgrade(req, {
      data: {
        socketId: Math.random(),
      },
    });
    if (success) return undefined;

    // handle HTTP request normally
    // ...
  },
  websocket: {
    // define websocket handlers
    async message(ws, message) {
      // the contextual dta is available as the `data` property
      // on the WebSocket instance
      console.log(`Received ${message} from ${ws.data.socketId}}`);
    },
  },
});

通常从传入请求中读取 cookie/标头以识别连接的客户端。

type WebSocketData = {
  createdAt: number;
  token: string;
  userId: string;
};

// TypeScript: specify the type of `data`
Bun.serve<WebSocketData>({
  async fetch(req, server) {
    // use a library to parse cookies
    const cookies = parseCookies(req.headers.get("Cookie"));
    const token = cookies["X-Token"];
    const user = await getUserFromToken(token);

    const upgraded = server.upgrade(req, {
      data: {
        createdAt: Date.now(),
        token: cookies["X-Token"],
        userId: user.id,
      },
    });

    if (upgraded) return undefined;
  },
  websocket: {
    async message(ws, message) {
      // save the message to a database
      await saveMessageToDatabase({
        message: String(message),
        userId: ws.data.userId,
      });
    },
  },
});