# @foxglove/ws-protocol 中文文档

规范地址：https://npmcn.com/package/%40foxglove/ws-protocol/

版本：0\.8\.0
npm 元数据更新时间：2025-03-13T19:53:08.433Z
中文译文更新时间：2026-11-15T10:40:37.477Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40foxglove/ws-protocol
原文对照：https://npmcn.com/package/%40foxglove/ws-protocol/?lang=original
项目主页：https://foxglove.dev/
源码仓库：https://github.com/foxglove/ws-protocol

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：339 kB，65 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2021-11-24T22:07:03.533Z
- 最新版本发布：2025-03-13T19:53:07.144Z
- 近 30 天下载量：150156（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：28（近 12 个月 0 个）

## 中文简介

Foxglove WebSocket 协议

## 安装

```sh
npm install @foxglove/ws-protocol
```

也可以使用：`pnpm add @foxglove/ws-protocol`、`yarn add @foxglove/ws-protocol`、`bun add @foxglove/ws-protocol`

## README

# Foxglove WebSocket 服务器和客户端

此软件包提供了服务器执行 [Foxglove WebSocket 协议](https://github.com/foxglove/ws-protocol)。本协议允许 [狐狸集团](https://foxglove.dev/) 输入任意“活”流数据.

## 安装

```
$ npm install @foxglove/ws-protocol
```

此软件包不需要特定的WebSocket服务器或客户端执行,所以您需要安装自己的软件包. 对于Node.js,你可以使用 [负](https://www.npmjs.com/package/ws) 软件包 :

```
$ npm install ws
```

## 实例

运行这些 [示例脚本](https://github.com/foxglove/ws-protocol/tree/main/typescript/ws-protocol-examples),在 TypeScript 中执行,以启动.

## 服务器模板

以下模板发布关于一个单一主题的信息 `example_msg`,使用 JSON 编码消息数据和 [杰森·斯克马](https://json-schema.org/) 来描述信件布局.

```js
const { FoxgloveServer } = require("@foxglove/ws-protocol");
const { WebSocketServer } = require("ws");

function delay(durationSec) {
  return new Promise((resolve) => setTimeout(resolve, durationSec * 1000));
}

async function main() {
  const server = new FoxgloveServer({ name: "example-server" });
  const ws = new WebSocketServer({
    port: 8765,
    handleProtocols: (protocols) => server.handleProtocols(protocols),
  });
  ws.on("listening", () => {
    console.log("server listening on %s", ws.address());
  });
  ws.on("connection", (conn, req) => {
    const name = `${req.socket.remoteAddress}:${req.socket.remotePort}`;
    console.log("connection from %s via %s", name, req.url);
    server.handleConnection(conn, name);
  });
  server.on("subscribe", (chanId) => {
    console.log("first client subscribed to %d", chanId);
  });
  server.on("unsubscribe", (chanId) => {
    console.log("last client unsubscribed from %d", chanId);
  });
  server.on("error", (err) => {
    console.error("server error: %o", err);
  });

  const ch1 = server.addChannel({
    topic: "example_msg",
    encoding: "json",
    schemaName: "ExampleMsg",
    schema: JSON.stringify({
      type: "object",
      properties: {
        msg: { type: "string" },
        count: { type: "number" },
      },
    }),
  });

  const textEncoder = new TextEncoder();
  let i = 0;
  while (true) {
    await delay(0.2);
    server.sendMessage(
      ch1,
      BigInt(Date.now()) * 1_000_000n,
      textEncoder.encode(JSON.stringify({ msg: "Hello!", count: ++i })),
    );
  }
}

main().catch(console.error);
```

将模板代码复制到一个文件并运行它(例如. `node server.js`) (中文(简体) ). 然后,对文件进行必要的调整,使这个简单的服务器自定义到您想要的规格.

## 客户端模板

下面的模板订阅所有频道使用此程序的信息 `json` 编码 见 [`@foxglove/ws-protocol-examples`](https://github.com/foxglove/ws-protocol/tree/main/typescript/ws-protocol-examples#example-client) 例如,客户端使用 `protobuf` 编码.

```js
const { FoxgloveClient } = require("@foxglove/ws-protocol");
const { WebSocket } = require("ws");

async function main() {
  const client = new FoxgloveClient({
    ws: new WebSocket(`ws://localhost:8765`, [FoxgloveClient.SUPPORTED_SUBPROTOCOL]),
  });
  const deserializers = new Map();
  client.on("advertise", (channels) => {
    for (const channel of channels) {
      if (channel.encoding !== "json") {
        console.warn(`Unsupported encoding ${channel.encoding}`);
        continue;
      }
      const subId = client.subscribe(channel.id);
      const textDecoder = new TextDecoder();
      deserializers.set(subId, (data) => JSON.parse(textDecoder.decode(data)));
    }
  });
  client.on("message", ({ subscriptionId, timestamp, data }) => {
    console.log({
      subscriptionId,
      timestamp,
      data: deserializers.get(subscriptionId)(data),
    });
  });
}

main().catch(console.error);
```

将模板代码复制成文件(例如. `client.js`开始一个 [Foxglove Websocket 服务器](https://npmcn.com/package/%40foxglove/ws-protocol/#readme-server-template)。在单独的终端窗口中,运行客户端代码(例如:. `node client.js`) (中文(简体) ).

如果您的服务器和客户端运行正确, 您应该看到以下输出 :

```
$ node client.js
{
  subscriptionId: 0,
  timestamp: 1638999307183000000n,
  data: { msg: 'Hello!', count: 2849 }
}
{
  subscriptionId: 0,
  timestamp: 1638999307384000000n,
  data: { msg: 'Hello!', count: 2850 }
}
...
```

对文件作必要的调整来自定义这个简单的客户端.

## 发展

这个软件包生活在一个使用 [纱线工作空间](https://yarnpkg.com/features/workspaces),所以大多数命令(除 `yarn install`) 应为前缀 `yarn workspace @foxglove/ws-protocol ...`。 。 。 .

-   `yarn install` - 安装发展依赖
-   `yarn workspace @foxglove/ws-protocol version --patch` (或 `--minor` 或者说 `--major`) — 增加版本编号并创建适当的 git 标签

## 常见问题

### @foxglove/ws-protocol 是什么？

Foxglove WebSocket 协议

### 如何安装 @foxglove/ws-protocol？

在项目目录运行 npm install @foxglove/ws-protocol，或使用 pnpm add / yarn add / bun add。

### @foxglove/ws-protocol 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @foxglove/ws-protocol 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @foxglove/ws-protocol 可以商用吗？

@foxglove/ws-protocol 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @foxglove/ws-protocol 的下载量有多少？

根据 npm 官方下载统计，@foxglove/ws-protocol 在 2026/10/16 – 2026/11/14 这 30 天内被下载 150,156 次，日均约 5,005 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @foxglove/ws-protocol 还在维护吗？

最新版本 0\.8\.0 发布于 2025/03/14（1\.7 年前）；至今共发布 28 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/11/25。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

