> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 构建简单的 WebSocket 服务器

使用 [`Bun.serve`](/runtime/http/server) 启动 WebSocket 服务器。

在 `fetch` 中，`server.upgrade()` 尝试将传入的 `ws:` 或 `wss:` 请求升级为 WebSocket 连接。

```ts server.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
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(`收到：${message}`);
      // 发送回复消息
      ws.send(`你说了：${message}`);
    },
  },
});

console.log(`监听于 ${server.hostname}:${server.port}`);
```
