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

# WebSocket 编码 - JSON、MessagePack 与 zstd

> Apexium API WebSocket 的三种编码、生产环境接受哪一种，以及如何在 Python 和 Node.js 中解码。

您在登录时用 `receiveType` 选择频道消息的编码。

| `receiveType` | 帧 | 内容 |
| - | - | - |
| `json` | 文本 | JSON 格式的封装 |
| `binary` | 二进制 | [MessagePack](https://msgpack.org) 格式的封装 |
| `zstd` | 二进制 | 用 [zstd](https://facebook.github.io/zstd/) 压缩的 JSON 封装 |

> [!WARNING]
>
> 生产环境只接受 `zstd`。使用其他 `receiveType` 的登录会以 `4001` 被拒绝。对于关注大量赛事的客户端，赔率数据流可达每秒数兆比特，zstd 可将其缩小约四倍。

* **控制帧。** `login_ok`、`subscribed`、`snapshot_required`、`error` 以及其他控制帧始终是 JSON 文本帧，与 `receiveType` 无关。可按帧类型区分：文本帧是控制帧，二进制帧是频道消息。
* **一帧一条消息。** 每个二进制帧恰好包含一条单独压缩的消息。没有字典，帧与帧之间没有状态。

## 在 Python 中解码

使用 [`websockets`](https://pypi.org/project/websockets/) 和 [`zstandard`](https://pypi.org/project/zstandard/)：

```python theme={null}
import asyncio
import json

import websockets
import zstandard

URL = "wss://api.apexiumbet.com/v1/ws"
LOGIN = {
    "type": "login",
    "apiKey": "apx_live_…",
    "receiveType": "zstd",
    "channels": ["odds", "orders"],
    "fixtureIds": ["id1000001770366972"],
}

decompressor = zstandard.ZstdDecompressor()


async def main():
    async with websockets.connect(URL) as ws:
        await ws.send(json.dumps(LOGIN))
        async for frame in ws:
            if isinstance(frame, str):
                control = json.loads(frame)
                print("control", control["type"], control)
                continue
            message = json.loads(decompressor.decompress(frame))
            print(message["channel"], message["type"], message["ts"])


asyncio.run(main())
```

如使用 `binary`，请改用 [`msgpack`](https://pypi.org/project/msgpack/) 解码：`message = msgpack.unpackb(frame)`。

## 在 Node.js 中解码

Node.js 22.15 及以上版本原生支持 zstd 解压。使用 [`ws`](https://www.npmjs.com/package/ws)：

```js theme={null}
import { zstdDecompressSync } from 'node:zlib';
import WebSocket from 'ws';

const ws = new WebSocket('wss://api.apexiumbet.com/v1/ws');

ws.on('open', () =>
  ws.send(
    JSON.stringify({
      type: 'login',
      apiKey: 'apx_live_…',
      receiveType: 'zstd',
      channels: ['odds', 'orders'],
      fixtureIds: ['id1000001770366972'],
    })
  )
);

ws.on('message', (data, isBinary) => {
  if (!isBinary) {
    const control = JSON.parse(data.toString());
    console.log('control', control.type, control);
    return;
  }
  const message = JSON.parse(zstdDecompressSync(data).toString());
  console.log(message.channel, message.type, message.ts);
});
```

如使用 `binary`，请改用 [`msgpackr`](https://www.npmjs.com/package/msgpackr) 解码：`const message = unpack(data)`。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.