罗广辉
2026-04-24 648904d076ae6e17892b40675598b1c8dc474277
Merge branch 'feature/v9.0/9.0.3' into feature/v9.0/9.0.4
1 files modified
23 ■■■■■ changed files
src/hooks/useGlobalWS.js 23 ●●●●● patch | view | raw | blame | history
src/hooks/useGlobalWS.js
@@ -3,6 +3,7 @@
import useAppStore from "../store/modules/app/index.js";
let socketTask = null
let heartbeatTimer = null
export function useGlobalWS() {
    const userStore = useUserStore();
@@ -36,6 +37,7 @@
    // 关闭ws
    function closeWS() {
    stopHeartbeat()
        socketTask?.close({
            success: () => {
                console.log('ws关闭连接');
@@ -76,7 +78,7 @@
    // 监听连接关闭
    socketTask.onClose((res) => {
      console.log(`WebSocket连接关闭,代码: ${res.code}, 原因: ${res.reason}`)
      startHeartbeat()
      // 根据不同的关闭代码处理
      if (res.code === 1000) { // 正常关闭
        console.log('连接正常关闭')
@@ -95,6 +97,25 @@
    })
    }
  function startHeartbeat() {
    stopHeartbeat()
    heartbeatTimer = setInterval(() => {
      if (socketTask && socketTask.readyState === 1) {
        // 尝试以 JSON 格式发送,并降低频率(30秒一次)以减少服务器负担
        socketTask.send({
          data: JSON.stringify({ type: 'ping', timestamp: Date.now() })
        });
      }
    }, 30000)
  }
  function stopHeartbeat() {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer)
      heartbeatTimer = null
    }
  }
    watch(access_token, initWS, {immediate: true})
}