Browse Source

feat: 客户端始终保持websocket重连

Michael Wang 3 năm trước cách đây
mục cha
commit
778b6434d7
1 tập tin đã thay đổi với 19 bổ sung0 xóa
  1. 19 0
      src/features/OnlineExam/Examing/ws.js

+ 19 - 0
src/features/OnlineExam/Examing/ws.js

@@ -9,6 +9,7 @@ let heartbeatIds = [];
 const RECONNECT_INTERVAL = 6 * 1000;
 const HEARTBEAT_INTERVAL = 50 * 1000;
 let reconnectNumber = 0;
+let stayAlive = false;
 
 export function openWS({ examRecordDataId }) {
   window._hmt.push(["_trackEvent", "websocket", "准备连接"]);
@@ -31,8 +32,15 @@ export function openWS({ examRecordDataId }) {
       closable: true,
     });
     console.log("WS init failed", examRecordDataId);
+    createLog({
+      type: "微信小程序websocket",
+      action: "Websocket初始化失败",
+      examRecordDataId,
+    });
   }
 
+  stayAlive = true;
+
   ws.onopen = (event) => {
     console.log("open ws", event);
     createLog({ type: "微信小程序websocket", action: "连接成功" });
@@ -46,6 +54,7 @@ export function openWS({ examRecordDataId }) {
         type: "微信小程序websocket",
         action: "ws closed by server",
         detail: JSON.stringify(event),
+        stayAlive,
       });
       for (const heartbeatId of heartbeatIds) {
         clearInterval(heartbeatId);
@@ -84,6 +93,15 @@ export function openWS({ examRecordDataId }) {
       } else {
         shouldReconnect = true; // reset shouldReconnect
       }
+
+      if (stayAlive) {
+        createLog({
+          type: "微信小程序websocket",
+          action: "连接被关闭后-客户端不允许关闭-准备连接",
+          detail: "onclose",
+        });
+        openWS({ examRecordDataId });
+      }
     };
 
     heartbeat();
@@ -149,6 +167,7 @@ function heartbeat() {
 export function closeWsWithoutReconnect() {
   createLog({ type: "微信小程序websocket", action: "客户端准备关闭ws。" });
   shouldReconnect = false;
+  stayAlive = false;
   try {
     if (ws && ws.readyState === 1) ws.close();
   } catch (e) {