Bun

指南WebSocket

使用 Bun 构建一个简单的 WebSocket 服务器

使用 Bun.serve 启动一个简单的 WebSocket 服务器。

fetch 中,我们尝试将传入的 ws:wss: 请求升级为 WebSocket 连接。

const server = Bun.serve<{ authToken: string }>({
  fetch(req, server) {
    const success = server.upgrade(req);
    if (success) {
      // Bun automatically returns a 101 Switching Protocols
      // if the upgrade succeeds
      return undefined;
    }

    // handle HTTP request normally
    return new Response("Hello world!");
  },
  websocket: {
    // this is called when a message is received
    async message(ws, message) {
      console.log(`Received ${message}`);
      // send back a message
      ws.send(`You said: ${message}`);
    },
  },
});

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