執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

建置一個簡單的 WebSocket 伺服器

使用 Bun.serve 啟動 WebSocket 伺服器。

在 fetch 中,server.upgrade() 會嘗試將傳入的 ws: 或 wss: 請求升級為 WebSocket 連線。

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