Long před 1 dnem
rodič
revize
af9f33736d
1 změnil soubory, kde provedl 27 přidání a 25 odebrání
  1. 27 25
      src/utils/ImSocket.js

+ 27 - 25
src/utils/ImSocket.js

@@ -2,62 +2,64 @@ export class ImSocket {
   /**
    * @param {string} url - WebSocket 服务器地址
    * @param {number} checkInterval - 检查连接状态的时间间隔,单位毫秒
-   * @param {number} reconnectDelay - 连接断开后重连的延迟,单位毫秒
    */
-  constructor(url, checkInterval = 5000, reconnectDelay = 3000) {
+  constructor(url, checkInterval = 5000) {
     this.url = url;
     this.checkInterval = checkInterval;
-    this.reconnectDelay = reconnectDelay;
     this.ws = null;
-    this.isManualClose = false;
+    this.onMessageCallback = null;
+    this.isConnecting = false;
     this.connect();
     this.startHeartbeat();
-    this.onMessageCallback = null;
   }
 
   connect() {
-    this.ws = new WebSocket(this.url);
+    if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
+      return;
+    }
+
+    if (this.isConnecting) {
+      return;
+    }
 
-    // 绑定事件
-    this.ws.onopen = (event) => {};
+    this.isConnecting = true;
+
+    this.ws = new WebSocket(this.url);
 
     this.ws.onmessage = (event) => {
       // 根据需要处理消息
       if (this.onMessageCallback) this.onMessageCallback(event.data);
     };
 
-    this.ws.onerror = (error) => {};
-
     this.ws.onclose = (event) => {
-      // 如果不是主动关闭,则重连
-      if (!this.isManualClose) {
-        setTimeout(() => this.reconnect(), this.reconnectDelay);
-      }
+      this.isConnecting = false;
     };
   }
 
-  reconnect() {
-    this.connect();
-  }
-
   // 定时检查连接状态
   startHeartbeat() {
+    if (this.heartbeatTimer) return;
+
     this.heartbeatTimer = setInterval(() => {
       if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
-        this.reconnect();
+        this.connect();
       }
     }, this.checkInterval);
   }
 
-  // 主动关闭 WebSocket 连接,并清除定时任务
-  close() {
-    this.isManualClose = true;
+   // 清除重连定时器的方法
+  stopHeartbeat() {
     if (this.heartbeatTimer) {
       clearInterval(this.heartbeatTimer);
+      this.heartbeatTimer = null;
     }
-    if (this.ws) {
-      this.ws.close();
-    }
+  }
+
+  // 主动关闭 WebSocket 连接,并清除定时任务
+  close() {
+    this.stopHeartbeat();
+    this.ws?.close();
+    this.ws = null;
   }
   onMessage(callback) {
     this.onMessageCallback = callback;