@cf-platform/cim
v2.0.0
Published
CIM 协议传输层 — WebSocket + Protobuf 编解码
Readme
@cf-platform/cim
基于 WebSocket 的 CIM 协议传输层库,负责 Protobuf 编解码和 WebSocket 连接管理。不包含心跳检测、自动重连、认证流程等业务逻辑——这些由上层 @cf-platform/mq 的 CimAdapter 提供。
定位
┌─────────────────────────────────┐
│ @cf-platform/mq (业务层) │
│ • 心跳管理 / 重连策略 / 鉴权流程 │
├─────────────────────────────────┤
│ @cf-platform/cim (传输层) ← 本库 │
│ • WebSocket 连接 │
│ • Protobuf 编解码 (Message/ │
│ ReplyBody/SentBody) │
│ • PING→PONG 自动响应 │
└─────────────────────────────────┘特性
- 🔌 WebSocket 连接 — 纯粹的 WebSocket 生命周期管理
- 📦 Protobuf 编解码 — 手写轻量 Protobuf 实现,零外部依赖(无 google-protobuf/Closure Library)
- 🔢 int64 varint — varint 编解码完整支持 int64(时间戳 / ID 等),不被截断到 32 位
- ⚡ PING/PONG — 自动响应服务端心跳
- 🎯 类型安全 — 完整 TypeScript 类型定义
- 🪶 极轻量 — ES 包仅 ~10.5 kB (gzip ~2.9 kB)
安装
npm install @cf-platform/cim快速开始
import { CIM } from '@cf-platform/cim'
const cim = new CIM({
url: 'wss://127.0.0.1:8080'
})
// 绑定回调
cim.onOpen = (event) => console.log('WebSocket 已连接')
cim.onMessage = (msg) => console.log('收到消息:', msg)
cim.onReply = (reply) => console.log('收到回复:', reply)
cim.onClose = (event) => console.log('连接关闭:', event.code)
cim.onError = (event) => console.error('连接错误')
cim.onPing = () => console.log('收到服务端心跳')
// 建立连接
cim.connect()
// 发送消息
cim.sendMessage({
key: 'send_message',
content: 'Hello World',
receiver: 'user456'
})
// 关闭连接
cim.close()提示:大多数场景下你不需要直接使用本库,推荐使用
@cf-platform/mq的createCimMq(),它在本库之上提供了心跳检测、自动重连、认证管理等完整功能。
API 文档
CIMOptions
| 参数 | 类型 | 默认值 | 必填 | 描述 |
|------|------|--------|------|------|
| url | string | - | ✓ | WebSocket 服务器地址(ws:// 或 wss://) |
| protocols | string \| string[] | - | | WebSocket 子协议 |
CIM 类
构造函数
constructor(options: CIMOptions)连接管理
| 方法 | 返回值 | 描述 |
|------|--------|------|
| connect() | void | 建立 WebSocket 连接 |
| reconnect() | void | 重新连接(等价于 close + connect) |
| close() | void | 关闭连接,清理所有事件监听 |
消息发送
| 方法 | 返回值 | 描述 |
|------|--------|------|
| sendMessage(data) | boolean | 编码为 Protobuf 并发送,返回是否成功 |
| sendPong() | void | 发送 PONG 心跳响应(通常由内部自动调用) |
状态查询
| 方法 | 返回值 | 描述 |
|------|--------|------|
| getConnectionState() | number | WebSocket readyState (0-3) |
| isConnected() | boolean | readyState === OPEN |
| isConnecting() | boolean | readyState === CONNECTING |
| isClosing() | boolean | readyState === CLOSING |
| isClosed() | boolean | readyState === CLOSED |
回调钩子
| 回调 | 类型 | 触发时机 |
|------|------|----------|
| onOpen | (event: Event) => void | WebSocket 连接建立 |
| onClose | (event: CloseEvent) => void | WebSocket 连接关闭 |
| onError | (event: Event) => void | WebSocket 连接错误 |
| onMessage | (msg: ReceivedMessage) => void | 收到 Protobuf 解码后的普通消息 |
| onReply | (reply: ReplyMessage) => void | 收到 Protobuf 解码后的回复消息 |
| onPing | () => void | 收到服务端 PING(上层可用于心跳超时重置) |
导出的枚举和常量
MessageType
enum MessageType {
PONG = 0, // 客户端发送心跳
PING = 1, // 服务端发送心跳
MESSAGE = 2, // 服务端发送消息
SENT_BODY = 3, // 客户端发送消息
REPLY_BODY = 4 // 服务端回复消息
}AuthenticationConstants
const AuthenticationConstants = {
PONG_BODY: new Uint8Array([80, 79, 78, 71]),
CODE_UNAUTHORIZED: '401',
CODE_OK: '200',
CLIENT_BIND: 'client_bind',
CLIENT_CLOSED: 'client_closed',
CLIENT_HANDSHAKE: 'client_handshake',
FORCE_OFFLINE: '999'
}类型定义
// 发送消息结构(protobuf map<string,string>,value 仅支持 string)
interface CIMMessage {
key: string
[key: string]: string
}
// 解码后的普通消息
interface ReceivedMessage {
action?: string
content?: string
sender?: string
receiver?: string
timestamp?: number
[key: string]: any
}
// 解码后的回复消息
interface ReplyMessage {
code: string
key: string
message: string
timestamp: number
data: Record<string, any>
}与 @cf-platform/mq 的关系
本库是 CIM 协议的传输层实现。如需完整功能,请使用 @cf-platform/mq:
| 功能 | @cf-platform/cim | @cf-platform/mq (CimAdapter) | |------|:---:|:---:| | WebSocket 连接 | ✅ | ✅ | | Protobuf 编解码 | ✅ | ✅ | | PING→PONG 响应 | ✅ | ✅ | | 心跳超时检测 | ❌ | ✅ | | 自动重连 | ❌ | ✅ | | CLIENT_BIND 认证 | ❌ | ✅ | | HANDSHAKE 鉴权 | ❌ | ✅ | | 强制下线处理 | ❌ | ✅ | | EventManager 事件 | ❌ | ✅ |
更新日志
v2.0.1 (修复)
- 🐛 修复 varint 64 位截断 —
readVarint/writeVarint原先用>>> 0截断到 uint32,导致timestamp/id等 int64 字段在Date.now()量级(> 2^32)时丢失高位。现改用「低位按位 + 高位加权」/「取模分段」实现,正确支持到Number.MAX_SAFE_INTEGER - 🐛 修复 map 反序列化字段顺序依赖 —
ReplyBody/SentBody的map<string,string>反序列化原先假定 entry 内 key(字段1) 在 value(字段2) 之前。现用临时变量收集后统一 set,兼容任意字段顺序 - 🧹 移除未使用的
_manualClose内部状态
v2.0.0 (重构)
- 🔥 Breaking: 移除心跳检测、自动重连、认证流程 — 迁移至
@cf-platform/mq的 CimAdapter - 🔥 Breaking: 移除
CustomEvents、LoginConfiguration、LoginParams类型 - 🔥 Breaking:
CIMOptions精简为url+protocols - 🆕 Protobuf 手写 TS 实现,移除 google-protobuf 依赖(SDK 体积从 ~8000 行降至 ~270 行)
- 🆕 新增
onPing、onReply回调钩子 - ✨ CIM 退化为纯传输层,职责单一
许可证
ISC
