Skip to main content
使用 Bun.serve 启动一个简单的 WebSocket 服务器。 fetch 中,我们尝试将传入的 ws:wss: 请求升级为 WebSocket 连接。
https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217server.ts
const server = Bun.serve({
  fetch(req, server) {
    const success = server.upgrade(req);
    if (success) {
      // 如果升级成功,Bun 会自动返回 101 Switching Protocols
      return undefined;
    }

    // 正常处理 HTTP 请求
    return new Response("Hello world!");
  },
  websocket: {
    // TypeScript:像这样指定 ws.data 的类型
    data: {} as { authToken: string },

    // 当接收到消息时调用此函数
    async message(ws, message) {
      console.log(`Received ${message}`);
      // 发送回复消息
      ws.send(`You said: ${message}`);
    },
  },
});

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