Browse Source

pref: 优化socket

charlie 3 months ago
parent
commit
9bff8d2cb7
1 changed files with 30 additions and 11 deletions
  1. 30 11
      src/api/index.js

+ 30 - 11
src/api/index.js

@@ -366,13 +366,20 @@ export const initSocket = (obj, getMessage) => {
   // }
   // 测试模拟发送消息end!!!!
   if (window.socket) {
+    if (!window.socket.connected) {
+      window.socket.connect();
+    }
     return;
   }
+  const MAX_RECONNECTION_ATTEMPTS = 20;
   window.socket = io(obj.serverIP + ':' + obj.serverPort, {
-    reconnectionAttempts: 0,
     reconnection: true,
+    reconnectionAttempts: MAX_RECONNECTION_ATTEMPTS,
+    reconnectionDelay: 1000,
+    reconnectionDelayMax: 5000,
+    timeout: 20000,
     transports: ['websocket'],
-    forceNew: true,
+    forceNew: false,
     query: {
       type: 'C',
       deviceID: obj.deviceID,
@@ -381,9 +388,6 @@ export const initSocket = (obj, getMessage) => {
   // window.socket = new WebSocket('http://m00.puruiit.cn:10015/socket.io/?type=C&deviceID=8e5604af-99db-47a5-b5e9-465040486690&EIO=4&transport=websocket');
   window.socket.on('connect_timeout', function () {
     console.log('connect_timeout');
-    window.socket.close();
-    window.socket = null;
-    initSocket(obj, getMessage);
     Toast.show({
       duration: 10000,
       content: 'scoket连接超时',
@@ -398,13 +402,10 @@ export const initSocket = (obj, getMessage) => {
     // });
     if (!handler) {
       handler = Modal.show({
-        content: '连接断开' + e,
+        content: '连接断开' + (e?.message || e),
         closeOnMaskClick: true,
       });
     }
-    window.socket.close();
-    window.socket = null;
-    initSocket(obj, getMessage);
   });
   //服务器响应消息
   window.socket.on('callNumber', (data) => {
@@ -438,7 +439,25 @@ export const initSocket = (obj, getMessage) => {
         closeOnMaskClick: true,
       });
     }
-    // window.socket = null;
-    // initSocket(obj, getMessage);
+    if (e === 'io server disconnect') {
+      window.socket.connect();
+    }
+  });
+
+  window.socket.on('reconnect_attempt', function (attempt) {
+    console.log('reconnect_attempt', attempt, '/', MAX_RECONNECTION_ATTEMPTS);
+  });
+
+  window.socket.on('reconnect', function (attempt) {
+    console.log('reconnect success on attempt', attempt);
+  });
+
+  window.socket.on('reconnect_failed', function () {
+    console.log('reconnect_failed, recreate socket');
+    if (window.socket) {
+      window.socket.close();
+      window.socket = null;
+    }
+    setTimeout(() => initSocket(obj, getMessage), 1000);
   });
 };