罗广辉
2026-04-24 040ec887cfa2794c0c3203d459b033bfd7a08e48
src/hooks/useGlobalWS.js
@@ -1,9 +1,9 @@
import {useUserStore} from "@/store/index.js";
import {getEnvObj} from "@/utils/index.js";
import {enterRoom} from "@/utils/voiceCallByTX/index.js";
import useAppStore from "../store/modules/app/index.js";
let socketTask = null
let heartbeatTimer = null
export function useGlobalWS() {
   const userStore = useUserStore();
@@ -30,9 +30,6 @@
               url: '/pages/login/index'
            })
            break
         case 'VoiceCall':
            enterRoom(payload, userId.value)
            break
         default:
            break;
      }
@@ -40,6 +37,7 @@
   // 关闭ws
   function closeWS() {
    stopHeartbeat()
      socketTask?.close({
         success: () => {
            console.log('ws关闭连接');
@@ -80,7 +78,7 @@
    // 监听连接关闭
    socketTask.onClose((res) => {
      console.log(`WebSocket连接关闭,代码: ${res.code}, 原因: ${res.reason}`)
      startHeartbeat()
      // 根据不同的关闭代码处理
      if (res.code === 1000) { // 正常关闭
        console.log('连接正常关闭')
@@ -99,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})
}