> ## 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 消息压缩

可以通过 `perMessageDeflate` 参数启用逐消息压缩。设置后，所有消息都会使用 [permessage-deflate](https://tools.ietf.org/html/rfc7692) 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"}}
Bun.serve({
  // ...
  websocket: {
    // 启用压缩
    perMessageDeflate: true,
  },
});
```

***

要为单个消息启用压缩，请在调用 `ws.send()` 时传入第二个参数 `true`。

```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"}}
Bun.serve({
  // ...
  websocket: {
    async message(ws, message) {
      // 发送压缩消息
      ws.send(message, true);
    },
  },
});
```
