WebSocket 封装库文档
功能概述
本 WebSocket 封装类主要实现以下核心功能:
- 自动心跳检测机制
- 断线自动重连
- 消息事件处理
- 可控连接关闭
- 超时断开保护
类结构
构造函数参数
参数名 | 类型 | 说明 |
---|---|---|
tk | string | 用户认证令牌 |
onOkCallBack | function | 消息接收回调函数 |
heartbeat | boolean | 是否启用心跳检测 |
timeout | number | 心跳发送间隔(毫秒) |
disconnectTime | number | 等待响应超时时间(毫秒) |
具体代码
import { apiTypeConfig } from "./common";
class NewWebSocket {
constructor(props) {
this.props = props;
this.tk = props.tk;
this.onOkCallBack = props.onOkCallBack;
this.heartbeat = props.heartbeat;
this.timeout = props.timeout;
this.disconnectTime = props.disconnectTime;
this.WS = null;
this.timeoutObj = null;
this.reconnectTime = null;
this.serverTimeoutObj = null;
this.lockReconnect = false;
}
/**
* 建立联系
*/
handleCreate() {
this.heartbeat = this.props.heartbeat;
const { domain, subdomain } = apiTypeConfig[API_TYPE] || { domain: "", subdomain: "" };
this.WS = new WebSocket(`wss://${subdomain}.${domain}/websocket/userMessage/${this.tk}`);
this.WS.onopen = () => {
if (this.heartbeat) {
this.handleSend("ping"); //第一次建立连接发送心跳(后端需求)
this.reset();
this.start();
}
};
this.WS.onmessage = e => {
if (this.heartbeat && e.data === "pong") {
this.reset();
this.start();
} else {
this.onOkCallBack(e.data);
}
};
this.WS.onclose = () => {
if (this.heartbeat) {
this.reconnect();
}
};
}
/**
* 断开连接
*/
handleClose(type) {
if (type === "end") {
this.heartbeat = false;
this.reset();
clearTimeout(this.reconnectTime);
this.reconnectTime = null;
}
this.WS.close();
}
/**
* 发送数据
* @param e 要发送的数据
*/
handleSend(e) {
this.WS.send(e);
}
/**
* 重置心跳
* @returns {NewWebSocket}
*/
reset() {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
this.timeoutObj = null;
this.serverTimeoutObj = null;
}
/**
* 发送心跳
*/
start() {
const that = this;
that.timeoutObj = setTimeout(function() {
that.handleSend("ping");
that.serverTimeoutObj = setTimeout(function() {
// 如果超过一定时间还没重置,说明后端主动断开了
that.handleClose();
}, that.disconnectTime);
}, that.timeout);
}
/**
* 延迟请求
*/
reconnect = () => {
const that = this;
if (this.lockReconnect) return;
this.lockReconnect = true;
this.reconnectTime = setTimeout(function() {
// 没连接上会一直重连,设置延迟避免请求过多
that.handleCreate();
that.lockReconnect = false;
}, 10000);
};
}
export default NewWebSocket;
使用示例子
const ws = new NewWebSocket({
tk: 'your_auth_token',
onOkCallBack: (data) => {
console.log('Received:', data);
},
heartbeat: true,
timeout: 30000, // 30秒发送一次心跳
disconnectTime: 5000 // 5秒无响应判定超时
});
// 建立连接
ws.handleCreate();
// 发送消息
ws.handleSend('Hello Server');
// 关闭连接
ws.handleClose('end');