chenyao
2026-04-22 cd1f367b9e0f50133e2b3e15b98d5301eb9a1606
feat:增加心跳机制
1 files modified
23 ■■■■■ changed files
src/hooks/useGlobalWS.js 23 ●●●●● patch | view | raw | blame | history
src/hooks/useGlobalWS.js
@@ -4,6 +4,7 @@
import useAppStore from "../store/modules/app/index.js";
let socketTask = null
let heartbeatTimer = null
export function useGlobalWS() {
    const userStore = useUserStore();
@@ -40,6 +41,7 @@
    // 关闭ws
    function closeWS() {
    stopHeartbeat()
        socketTask?.close({
            success: () => {
                console.log('ws关闭连接');
@@ -80,7 +82,7 @@
    // 监听连接关闭
    socketTask.onClose((res) => {
      console.log(`WebSocket连接关闭,代码: ${res.code}, 原因: ${res.reason}`)
      startHeartbeat()
      // 根据不同的关闭代码处理
      if (res.code === 1000) { // 正常关闭
        console.log('连接正常关闭')
@@ -99,6 +101,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})
}