he wei
2024-11-05 ae05c627c6b688d41e0770a6e5e3e2a4553f29ac
U websocket 重连机制
1个文件已修改
75 ■■■■ 已修改文件
src/hooks/useWebSocket.js 75 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/hooks/useWebSocket.js
@@ -11,10 +11,13 @@
export default function (url) {
  url = getWsUrl(url);
  // 重连时间间隔 默认5秒
  const reConnectDelay = 5 * 1000;
  const socket = ref(null);
  const isConnected = ref(false);
  const message = ref("");
  let timer = null;
  const sendCallback = reactive([]);
@@ -38,14 +41,13 @@
      message.value = event.data;
    };
    socket.value.onerror = (error) => {
      console.error("WebSocket Error:", error, url);
    socket.value.onerror = (Event) => {
      console.error("WebSocket Error:", Event, url);
      WSClose(Event);
    };
    socket.value.onclose = () => {
      isConnected.value = false;
      console.log("WebSocket 连接已关闭, url: ", url);
    };
    socket.value.onclose = WSClose;
  };
  // 发送数据
@@ -57,6 +59,63 @@
      sendCallback.push(() => sendData(data));
    }
  };
  function WSClose(Event) {
    isConnected.value = false;
    if (socket.value) {
      switch (socket.value.readyState) {
        case 0:
          socket.value.onopen = () => {
            socket.value.close();
            console.log('链接关闭', url, 'close事件对象:', Event);
            socket.value = null;
            // 没有event对象 则为手动关闭
            if (Event) {
              reConnect();
            }
          }
          break;
        case 1:
          socket.value.close();
          console.log('链接关闭', url, 'close事件对象:', Event);
          socket.value = null;
          // 没有event对象 则为手动关闭
          if (Event) {
            reConnect();
          }
          break;
        case 2:
          socket.value.onclose = () => {
            console.log('链接关闭', url, 'close事件对象:', Event);
            socket.value = null;
            // 没有event对象 则为手动关闭
            if (Event) {
              reConnect();
            }
          }
          break;
        case 3:
          console.log('链接关闭', url, 'close事件对象:', Event);
          socket.value = null;
          // 没有event对象 则为手动关闭
          if (Event) {
            reConnect();
          }
          break;
      }
    }
  }
  // 重连
  function reConnect() {
    if (timer) {
      return false;
    }
    timer = setTimeout(() => {
      timer = null;
      connect();
    }, reConnectDelay);
  }
  onMounted(() => {
    // console.log('socket mount', Date.now(), '=============');
@@ -74,13 +133,13 @@
  onDeactivated(() => {
    if (socket.value) {
      socket.value.close();
      WSClose();
    }
  });
  onUnmounted(() => {
    if (socket.value) {
      socket.value.close();
      WSClose();
    }
  });