feat(socket): 添加WebSocket自动重连机制

为WebSocket连接添加自动重连功能,包括最大重连次数、重连间隔时间以及重连逻辑,以提高连接稳定性
This commit is contained in:
From-wh 2025-03-31 11:40:27 +08:00
parent 3bf6028aee
commit ebd3111ee3

View File

@ -20,6 +20,9 @@ class wsSocket {
constructor(opt) {
this.ws = null;
this.opt = opt || {};
this.reconnectAttempts = 0;
this.reconnectMaxAttempts = 10; // 最大重连次数
this.reconnectInterval = 3000; // 重连间隔时间(ms)
this.init(opt.key);
}
@ -45,14 +48,20 @@ class wsSocket {
wsUrl = wsKefuSocketUrl;
}
if (wsUrl) {
this.ws = new WebSocket(wsUrl);
this.ws.onopen = this.onOpen.bind(this);
this.ws.onerror = this.onError.bind(this);
this.ws.onmessage = this.onMessage.bind(this);
this.ws.onclose = this.onClose.bind(this);
this.wsUrl = wsUrl;
this.key = key;
this.connect();
}
}
connect() {
this.ws = new WebSocket(this.wsUrl);
this.ws.onopen = this.onOpen.bind(this);
this.ws.onerror = this.onError.bind(this);
this.ws.onmessage = this.onMessage.bind(this);
this.ws.onclose = this.onClose.bind(this);
}
ping() {
var that = this;
this.timer = setInterval(function () {
@ -78,10 +87,24 @@ class wsSocket {
onClose() {
this.timer && clearInterval(this.timer);
this.opt.close && this.opt.close();
this.reconnect();
}
onError(e) {
this.opt.error && this.opt.error(e);
// 错误发生时不立即重连,等待onClose触发重连
}
reconnect() {
if (this.reconnectAttempts < this.reconnectMaxAttempts) {
this.reconnectAttempts++;
setTimeout(() => {
console.log(`WebSocket 尝试第 ${this.reconnectAttempts} 次重连...`);
this.connect();
}, this.reconnectInterval);
} else {
console.log('WebSocket 重连次数已达上限,停止重连');
}
}
$on(...args) {