cy-plugin-websocket
v2.0.5
Published
封装 websocket 插件
Readme
cy-plugin-websocket
一个功能完整的 WebSocket 客户端封装库,支持心跳、自动重连、事件监听等特性。
✨ 特性
- 🔄 自动重连 - 支持指数退避重连策略
- 💓 心跳机制 - 可配置的心跳检测
- 📦 消息队列 - 连接断开时自动缓存消息
- 🎯 事件系统 - 基于 Emittery 的事件监听
- 🛡️ 类型安全 - 完整的 TypeScript 支持
- 🔧 高度可配置 - 丰富的配置选项
📦 安装
npm install cy-plugin-websocket依赖要求
本项目依赖 emittery 作为事件系统,请确保已安装:
npm install [email protected] --save🚀 快速开始
基础用法
注意: 使用事件监听时,请使用 enumSocketEvent 枚举而不是字符串,这样可以获得更好的类型安全性和 IDE 支持。
import { SocketClient, enumSocketEvent } from 'cy-plugin-websocket';
// 创建 WebSocket 连接
const socket = new SocketClient('wss://example.com/ws');
// 建立连接
socket.connect();
// 监听事件
socket.on(enumSocketEvent.OPEN, () => {
console.log('连接已建立');
});
socket.on(enumSocketEvent.MESSAGE, (data) => {
console.log('收到消息:', data);
});
socket.on(enumSocketEvent.CLOSE, (code, reason) => {
console.log('连接已关闭:', code, reason);
});
socket.on(enumSocketEvent.ERROR, (error) => {
console.log('连接错误:', error);
});
// 发送消息
socket.send({ type: 'chat', message: 'Hello World' });
// 移除事件监听器
const messageHandler = (data) => {
console.log('收到消息:', data);
};
socket.on(enumSocketEvent.MESSAGE, messageHandler);
// 稍后移除监听器
socket.off(enumSocketEvent.MESSAGE, messageHandler);高级配置
import SocketClient, { enumSocketEvent } from 'cy-plugin-websocket';
const socket = new SocketClient('wss://example.com/ws', {
// 开启调试模式
debug: true,
// 开启自动重连
connectResend: true,
// 心跳配置
heartOption: {
message: { type: 'ping' },
interval: 30000 // 30秒心跳
},
// 重连配置
reconnectOption: {
maxCount: 5, // 最大重连次数
interval: 2000, // 重连间隔
maxInterval: 10000 // 最大重连间隔
},
// 自定义消息处理
handleMessage: (data) => {
console.log('处理消息:', data);
return data;
}
});
socket.connect();
// 使用 on 方法监听事件
socket.on(enumSocketEvent.OPEN, () => {
console.log('连接已建立');
});
socket.on(enumSocketEvent.MESSAGE, (data) => {
console.log('收到消息:', data);
});
// 使用 off 方法移除监听器
const errorHandler = (error) => {
console.log('连接错误:', error);
};
socket.on(enumSocketEvent.ERROR, errorHandler);
// 稍后移除错误监听器
socket.off(enumSocketEvent.ERROR, errorHandler);📚 API 文档
构造函数
new SocketClient(url: string, options?: ISocketOption)参数
url- WebSocket 服务器地址options- 配置选项(可选)
配置选项 (ISocketOption)
| 参数 | 类型 | 默认值 | 描述 |
| ----------------- | --------------------------------- | ------- | ---------------- |
| debug | boolean | false | 是否开启调试模式 |
| connectResend | boolean | false | 是否开启自动重连 |
| heartOption | ISocketHeartOption | - | 心跳配置 |
| reconnectOption | ISocketReconnectOption | - | 重连配置 |
| handleMessage | (data: MessageEvent) => unknown | - | 消息处理函数 |
心跳配置 (ISocketHeartOption)
| 参数 | 类型 | 默认值 | 描述 |
| ---------- | -------- | ------------------ | ---------------- |
| message | any | { beat: 'beat' } | 心跳消息内容 |
| interval | number | 3000 | 心跳间隔(毫秒) |
重连配置 (ISocketReconnectOption)
| 参数 | 类型 | 默认值 | 描述 |
| ------------- | -------- | ---------- | -------------------- |
| maxCount | number | Infinity | 最大重连次数 |
| interval | number | 5000 | 重连间隔(毫秒) |
| maxInterval | number | 60000 | 最大重连间隔(毫秒) |
方法
connect()
建立 WebSocket 连接
socket.connect();send(message: unknown)
发送消息
// 发送对象
socket.send({ type: 'chat', message: 'Hello' });
// 发送字符串
socket.send('Hello World');close()
主动关闭连接
socket.close();destroy()
销毁连接并清理资源
socket.destroy();on(event, listener)
添加事件监听器
import { enumSocketEvent } from 'cy-plugin-websocket';
// 监听连接建立事件
socket.on(enumSocketEvent.OPEN, () => {
console.log('连接已建立');
});
// 监听消息事件
const messageHandler = (data) => {
console.log('收到消息:', data);
};
socket.on(enumSocketEvent.MESSAGE, messageHandler);
// 监听连接关闭事件
socket.on(enumSocketEvent.CLOSE, (code, reason) => {
console.log('连接已关闭:', code, reason);
});
// 监听错误事件
socket.on(enumSocketEvent.ERROR, (error) => {
console.log('连接错误:', error);
});off(event, listener)
移除事件监听器
// 移除特定的消息监听器
socket.off(enumSocketEvent.MESSAGE, messageHandler);
// 移除所有错误监听器
socket.off(enumSocketEvent.ERROR);once(event, listener)
添加一次性事件监听器
// 只监听一次连接建立事件
socket.once(enumSocketEvent.OPEN, () => {
console.log('连接已建立,只执行一次');
});
// 只监听一次消息事件
socket.once(enumSocketEvent.MESSAGE, (data) => {
console.log('收到第一条消息:', data);
});offAll()
移除所有事件监听器
// 移除所有事件的所有监听器
socket.offAll();
// 通常在组件销毁时使用
socket.destroy();
socket.offAll();事件
| 事件 | 参数 | 描述 |
| --------- | ------------ | -------- |
| open | Event | 连接建立 |
| message | unknown | 收到消息 |
| close | CloseEvent | 连接关闭 |
| error | Event | 连接错误 |
属性
state
获取当前连接状态
const state = socket.state;
// 0: CONNECTING
// 1: OPEN
// 2: CLOSING
// 3: CLOSED