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

# 构建一个简单的 WebSocket 服务器

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

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

```ts server.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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}`);
```
