---
title: "WebSocket 快速开始"
canonical_url: "https://tweetstream.io/zh-cn/docs/quickstart"
last_updated: 2026-09-24
---

# WebSocket 快速开始

添加一个监控账号，打开服务端 WebSocket，然后输出每个 v1 消息信封。

Canonical URL: https://tweetstream.io/zh-cn/docs/quickstart

## 运行 5 分钟连通性测试

添加一个监控账号，复制示例并运行。看到 `TweetStream connected` 表示认证成功。该账号发布内容后会收到事件。

### 运行 TypeScript 连通性测试

```typescript
// bun add ws
// TWEETSTREAM_API_KEY=ts_... bun run smoke.ts
import WebSocket from "ws";

const apiKey = process.env.TWEETSTREAM_API_KEY;
if (!apiKey) {
  throw new Error("Missing TWEETSTREAM_API_KEY");
}

const ws = new WebSocket("wss://ws-global.tweetstream.io/ws", [
  "tweetstream.v1",
  `tweetstream.auth.token.${apiKey}`,
]);

ws.on("open", () => {
  console.log("TweetStream connected");
});

ws.on("message", (raw) => {
  const event = JSON.parse(raw.toString());
  console.log(event.t, event.op, event.d);
});

ws.on("close", (code, reason) => {
  console.log("TweetStream closed", code, reason.toString());
});

ws.on("unexpected-response", (_request, response) => {
  console.error(
    "Connection rejected",
    response.statusCode,
    response.statusMessage,
  );
  response.resume();
  process.exitCode = 1;
});

ws.on("error", (error) => {
  console.error("WebSocket error", error.message);
});
```

## 分发操作

每个事件在 `t` 中标明类别，在 `op` 中标明操作。交付参考列出全部 18 种服务端操作。

- [全部操作](https://tweetstream.io/zh-cn/docs/envelope-delivery-recovery-errors#operations): 每种服务端事件的类别、操作和含义。

## 让消费者可靠运行

- [连接详情](https://tweetstream.io/zh-cn/docs/connection-auth-heartbeat): 选择端点，并了解认证和心跳行为。
- [生产环境消费者](https://tweetstream.io/zh-cn/docs/production-consumer): 加入重连、事件分发和恢复检查点。
