Skip to main content
使用 Bun.serve 启动一个简单的 WebSocket 服务器。 fetch 中,我们尝试将传入的 ws:wss: 请求升级为 WebSocket 连接。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79server.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}`);