Procházet zdrojové kódy

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

为WebSocket连接添加自动重连功能,包括最大重连次数、重连间隔时间以及重连逻辑,以提高连接稳定性
From-wh před 9 měsíci
rodič
revize
ebd3111ee3
1 změnil soubory, kde provedl 28 přidání a 5 odebrání
  1. 28 5
      template/admin/src/libs/socket.js

+ 28 - 5
template/admin/src/libs/socket.js

@@ -20,6 +20,9 @@ class wsSocket {
   constructor(opt) {
   constructor(opt) {
     this.ws = null;
     this.ws = null;
     this.opt = opt || {};
     this.opt = opt || {};
+    this.reconnectAttempts = 0;
+    this.reconnectMaxAttempts = 10; // 最大重连次数
+    this.reconnectInterval = 3000; // 重连间隔时间(ms)
     this.init(opt.key);
     this.init(opt.key);
   }
   }
 
 
@@ -45,14 +48,20 @@ class wsSocket {
       wsUrl = wsKefuSocketUrl;
       wsUrl = wsKefuSocketUrl;
     }
     }
     if (wsUrl) {
     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() {
   ping() {
     var that = this;
     var that = this;
     this.timer = setInterval(function () {
     this.timer = setInterval(function () {
@@ -78,10 +87,24 @@ class wsSocket {
   onClose() {
   onClose() {
     this.timer && clearInterval(this.timer);
     this.timer && clearInterval(this.timer);
     this.opt.close && this.opt.close();
     this.opt.close && this.opt.close();
+    this.reconnect();
   }
   }
 
 
   onError(e) {
   onError(e) {
     this.opt.error && this.opt.error(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) {
   $on(...args) {