@foxglove/ws-protocol

中文文档
0.8.0发布于 2025/03/14MITTypeScriptESM + CJS构建来源已验证近 30 天下载 15万

Foxglove WebSocket protocol

原始使用文档
文档目录5 节
  1. Installation
  2. Examples
  3. Server template
  4. Client template
  5. Development

Foxglove WebSocket server and client

This package provides a server implementation of the Foxglove WebSocket protocol. This protocol enables Foxglove to ingest arbitrary “live” streamed data.

Installation

$ npm install @foxglove/ws-protocol

This package does not require a specific WebSocket server or client implementation, so you will need to install your own. For Node.js, you can use the ws package:

$ npm install ws

Examples

Run these example scripts, implemented in TypeScript, to get started.

Server template

The template below publishes messages on a single topic called example_msg, using JSON to encode message data and JSON Schema to describe the message layout.

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);

Copy the template code into a file and run it (e.g. node server.js). Then, make the necessary adjustments to the file to customize this simple server to your desired specifications.

Client template

The template below subscribes to messages on all channels that use the json encoding. See @foxglove/ws-protocol-examples for an example client that subscribes to messages with the protobuf encoding.

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);

Copy the template code into a file (e.g. client.js) and start up a Foxglove Websocket server. In a separate terminal window, run the client code (e.g. node client.js).

You should see the following output if both your server and client are running correctly:

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

Make the necessary adjustments to the file to customize this simple client.

Development

This package lives inside a monorepo that uses yarn workspaces, so most commands (other than yarn install) should be prefixed with yarn workspace @foxglove/ws-protocol ....

  • yarn install – Install development dependencies
  • yarn workspace @foxglove/ws-protocol version --patch (or --minor or --major) – Increment the version number and create the appropriate git tag

版本与发布记录

@foxglove/ws-protocol 共发布 28 个版本,首次发布于 2021/11/25;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.8.0latest2025/03/141.7 年前
0.7.52025/01/311.8 年前
0.7.42024/07/302 年前
0.7.32024/04/252 年前
0.7.22023/11/103 年前
0.7.12023/08/093 年前

关于 @foxglove/ws-protocol 的常见问题

@foxglove/ws-protocol 是什么?

Foxglove WebSocket protocol

如何安装 @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 和提交记录判断。