罗广辉
2026-04-24 648904d076ae6e17892b40675598b1c8dc474277
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();
@@ -15,7 +15,6 @@
   // 消息处理
   function messageHandler(payload) {
    console.log(payload.biz_code, '767')
      switch (payload.biz_code) {
         case 'JOB_ISREFRESH':
        appStore.setJobUpdateKeyAdd()
@@ -31,9 +30,6 @@
               url: '/pages/login/index'
            })
            break
         case 'VoiceCall':
            enterRoom(payload, userId.value)
            break
         default:
            break;
      }
@@ -41,6 +37,7 @@
   // 关闭ws
   function closeWS() {
    stopHeartbeat()
      socketTask?.close({
         success: () => {
            console.log('ws关闭连接');
@@ -55,7 +52,7 @@
      if (!access_token.value) return
      const url = VITE_APP_WS_API_URL
         + `?x-auth-token=${encodeURI(access_token?.value)}`
         + `&model_type=3&workspace-id=3eb00efc-f81e-4f9e-a793-9281fc9ca9c2`
         + `&model_type=3&workspace-id=${userId.value}`
      // 创建连接
      socketTask = uni.connectSocket({
         url: url,
@@ -81,7 +78,7 @@
    // 监听连接关闭
    socketTask.onClose((res) => {
      console.log(`WebSocket连接关闭,代码: ${res.code}, 原因: ${res.reason}`)
      startHeartbeat()
      // 根据不同的关闭代码处理
      if (res.code === 1000) { // 正常关闭
        console.log('连接正常关闭')
@@ -100,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})
}