From ebd3111ee300b23aeeaeab839a97b1acb48e4863 Mon Sep 17 00:00:00 2001 From: From-wh Date: Mon, 31 Mar 2025 11:40:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(socket):=20=E6=B7=BB=E5=8A=A0WebSocket?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E9=87=8D=E8=BF=9E=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为WebSocket连接添加自动重连功能,包括最大重连次数、重连间隔时间以及重连逻辑,以提高连接稳定性 --- template/admin/src/libs/socket.js | 33 ++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/template/admin/src/libs/socket.js b/template/admin/src/libs/socket.js index 67a374e19..f4c40f9f5 100644 --- a/template/admin/src/libs/socket.js +++ b/template/admin/src/libs/socket.js @@ -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) {