holly-websocket
v0.1.0
Published
holly-websocket SDK
Downloads
15
Readme
Holly WebSocket
开箱即用的 WebSocket 客户端 SDK,支持心跳检测和自动断线重连。
特性
- TypeScript 支持 - 完整的类型定义,提供优秀的开发体验
- 心跳检测 - 自动发送心跳消息,保持连接活跃
- 自动重连 - 连接断开时自动尝试重连,可配置重连策略
- 事件驱动 - 基于事件的 API 设计,易于使用
- 灵活配置 - 丰富的配置选项,满足各种使用场景
- 零依赖 - 基于浏览器原生 WebSocket API,无需额外依赖
- 开箱即用 - 提供合理的默认配置,快速上手
安装
npm install holly-websocket快速开始
import { WebSocketClient, WebSocketEventType } from 'holly-websocket';
// 创建客户端实例
const client = new WebSocketClient({
url: 'wss://your-websocket-server.com',
});
// 监听连接成功事件
client.on(WebSocketEventType.OPEN, () => {
console.log('WebSocket 连接已建立');
// 发送消息
client.send('Hello Server!');
// 发送 JSON 数据
client.sendJSON({ type: 'greeting', message: 'Hello!' });
});
// 监听消息事件
client.on(WebSocketEventType.MESSAGE, (data) => {
console.log('收到消息:', data.data);
});
// 监听连接关闭事件
client.on(WebSocketEventType.CLOSE, (data) => {
console.log('连接已关闭:', data);
});
// 监听错误事件
client.on(WebSocketEventType.ERROR, (error) => {
console.error('发生错误:', error);
});
// 建立连接
client.connect();
// 断开连接
// client.disconnect();API 文档
WebSocketClient
构造函数
new WebSocketClient(options: WebSocketClientOptions)配置选项 (WebSocketClientOptions)
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| url | string | - | 必填,WebSocket 服务器地址 |
| protocols | string \| string[] | - | WebSocket 子协议 |
| reconnect | boolean | true | 是否启用自动重连 |
| reconnectAttempts | number | 5 | 最大重连次数,-1 表示无限重连 |
| reconnectInterval | number | 5000 | 重连间隔时间(毫秒) |
| heartbeat | boolean | true | 是否启用心跳检测 |
| heartbeatInterval | number | 30000 | 心跳间隔时间(毫秒) |
| heartbeatTimeout | number | 5000 | 心跳超时时间(毫秒) |
| heartbeatMessage | string \| object | 'ping' | 心跳消息内容 |
| isHeartbeatResponse | (data: any) => boolean | - | 判断是否为心跳响应的函数 |
| connectTimeout | number | 10000 | 连接超时时间(毫秒) |
| immediateHeartbeat | boolean | false | 连接建立后是否立即发送心跳 |
| debug | boolean | false | 是否开启调试模式 |
方法
connect()
建立 WebSocket 连接。
client.connect(): voiddisconnect()
断开 WebSocket 连接。
client.disconnect(): voidsend()
发送消息。
client.send(data: string | ArrayBufferLike | Blob | ArrayBufferView): booleansendJSON()
发送 JSON 格式的消息。
client.sendJSON(data: any): booleanon()
注册事件监听器。
client.on<T>(event: WebSocketEventType, handler: WebSocketEventHandler<T>): voidoff()
移除事件监听器。
client.off<T>(event: WebSocketEventType, handler: WebSocketEventHandler<T>): voidoffAll()
移除所有事件监听器。
client.offAll(event?: WebSocketEventType): voidgetStatus()
获取当前连接状态。
client.getStatus(): WebSocketStatusisConnected()
判断是否已连接。
client.isConnected(): booleandestroy()
销毁客户端实例。
client.destroy(): void事件类型 (WebSocketEventType)
| 事件 | 数据类型 | 说明 |
|------|---------|------|
| OPEN | Event | 连接成功 |
| CLOSE | WebSocketCloseData | 连接关闭 |
| ERROR | WebSocketErrorData | 连接错误 |
| MESSAGE | WebSocketMessageData | 接收到消息 |
| RECONNECTING | ReconnectData | 正在重连 |
| RECONNECTED | Event | 重连成功 |
| RECONNECT_FAILED | ReconnectData | 重连失败 |
| HEARTBEAT_TIMEOUT | null | 心跳超时 |
连接状态 (WebSocketStatus)
CONNECTING- 连接中CONNECTED- 已连接DISCONNECTING- 断开连接中DISCONNECTED- 已断开RECONNECTING- 重连中
使用示例
基础使用
import { WebSocketClient, WebSocketEventType } from 'holly-websocket';
const client = new WebSocketClient({
url: 'wss://echo.websocket.org',
debug: true, // 开启调试模式
});
client.on(WebSocketEventType.OPEN, () => {
console.log('连接成功');
client.send('Hello!');
});
client.on(WebSocketEventType.MESSAGE, ({ data }) => {
console.log('收到消息:', data);
});
client.connect();自定义心跳
const client = new WebSocketClient({
url: 'wss://your-server.com',
heartbeat: true,
heartbeatInterval: 20000, // 20秒发送一次心跳
heartbeatTimeout: 3000, // 3秒未收到响应视为超时
heartbeatMessage: { type: 'ping' }, // 自定义心跳消息
isHeartbeatResponse: (data) => {
// 自定义心跳响应判断逻辑
return data?.type === 'pong';
},
});
client.on(WebSocketEventType.HEARTBEAT_TIMEOUT, () => {
console.log('心跳超时,连接可能已断开');
});
client.connect();自定义重连策略
const client = new WebSocketClient({
url: 'wss://your-server.com',
reconnect: true,
reconnectAttempts: 10, // 最多重连10次
reconnectInterval: 3000, // 每次重连间隔3秒
});
client.on(WebSocketEventType.RECONNECTING, ({ attempt, maxAttempts }) => {
console.log(`正在尝试重连... (${attempt}/${maxAttempts})`);
});
client.on(WebSocketEventType.RECONNECT_FAILED, ({ attempt }) => {
console.log(`重连失败,已尝试 ${attempt} 次`);
});
client.connect();无限重连
const client = new WebSocketClient({
url: 'wss://your-server.com',
reconnect: true,
reconnectAttempts: -1, // -1 表示无限重连
reconnectInterval: 5000,
});
client.connect();发送不同类型的消息
// 发送文本消息
client.send('Hello World');
// 发送 JSON 消息
client.sendJSON({
type: 'chat',
message: 'Hello',
timestamp: Date.now(),
});
// 发送二进制数据
const buffer = new ArrayBuffer(8);
client.send(buffer);
// 发送 Blob
const blob = new Blob(['Hello'], { type: 'text/plain' });
client.send(blob);完整示例:聊天应用
import { WebSocketClient, WebSocketEventType } from 'holly-websocket';
class ChatClient {
private ws: WebSocketClient;
constructor(url: string, username: string) {
this.ws = new WebSocketClient({
url,
reconnect: true,
reconnectAttempts: -1,
heartbeat: true,
heartbeatInterval: 30000,
debug: true,
});
this.setupEventHandlers();
}
private setupEventHandlers() {
this.ws.on(WebSocketEventType.OPEN, () => {
console.log('聊天室已连接');
this.sendMessage('加入了聊天室', 'system');
});
this.ws.on(WebSocketEventType.MESSAGE, ({ data }) => {
if (data.type === 'chat') {
this.onMessageReceived(data);
}
});
this.ws.on(WebSocketEventType.RECONNECTING, ({ attempt }) => {
console.log(`连接断开,正在重连... (第 ${attempt} 次)`);
});
this.ws.on(WebSocketEventType.ERROR, (error) => {
console.error('连接错误:', error);
});
}
connect() {
this.ws.connect();
}
sendMessage(message: string, type: string = 'chat') {
this.ws.sendJSON({
type,
message,
timestamp: Date.now(),
});
}
private onMessageReceived(data: any) {
console.log(`[${new Date(data.timestamp).toLocaleTimeString()}] ${data.message}`);
}
disconnect() {
this.ws.disconnect();
}
}
// 使用
const chat = new ChatClient('wss://your-chat-server.com', 'Alice');
chat.connect();
chat.sendMessage('大家好!');TypeScript 支持
本 SDK 使用 TypeScript 编写,提供完整的类型定义。
import {
WebSocketClient,
WebSocketEventType,
WebSocketStatus,
WebSocketClientOptions,
WebSocketMessageData,
WebSocketErrorData,
WebSocketCloseData,
ReconnectData,
} from 'holly-websocket';浏览器兼容性
本 SDK 基于浏览器原生 WebSocket API,支持所有现代浏览器:
- Chrome 16+
- Firefox 11+
- Safari 7+
- Edge 12+
- Opera 12.1+
在线示例
React + Webpack Demo
完整的 React 应用示例,展示如何在实际项目中使用本 SDK。
快速开始:
# 1. 启动 WebSocket 服务器
node examples/index.js
# 2. 在另一个终端启动 React 应用
cd example/react-demo
npm install
npm run dev访问 http://localhost:3000 查看示例。
功能演示:
- WebSocket 连接管理
- 消息收发(文本、JSON)
- 自动重连机制
- 心跳检测
- 事件日志
- 统计信息
更多示例请查看 example 目录。
License
MIT
贡献
欢迎提交 Issue 和 Pull Request!
