From 648904d076ae6e17892b40675598b1c8dc474277 Mon Sep 17 00:00:00 2001
From: 罗广辉 <guanghui.luo@foxmail.com>
Date: Fri, 24 Apr 2026 16:21:12 +0800
Subject: [PATCH] Merge branch 'feature/v9.0/9.0.3' into feature/v9.0/9.0.4
---
src/hooks/useGlobalWS.js | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++----
1 files changed, 55 insertions(+), 4 deletions(-)
diff --git a/src/hooks/useGlobalWS.js b/src/hooks/useGlobalWS.js
index 450c29a..edb84c8 100644
--- a/src/hooks/useGlobalWS.js
+++ b/src/hooks/useGlobalWS.js
@@ -1,11 +1,14 @@
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();
+ const appStore = useAppStore();
+
const userId = computed(() => userStore?.userInfo?.user_id)
const access_token = computed(() => userStore?.userInfo?.access_token)
const {VITE_APP_WS_API_URL} = getEnvObj()
@@ -14,8 +17,10 @@
function messageHandler(payload) {
switch (payload.biz_code) {
case 'JOB_ISREFRESH':
+ appStore.setJobUpdateKeyAdd()
break
case 'DEVICE_ISREFRESH':
+ appStore.setDeviceUpdateKeyAdd()
break
case 'DOWNLOAD_PROGRESS':
break
@@ -25,9 +30,6 @@
url: '/pages/login/index'
})
break
- case 'VoiceCall':
- enterRoom(payload, userId.value)
- break
default:
break;
}
@@ -35,6 +37,7 @@
// 关闭ws
function closeWS() {
+ stopHeartbeat()
socketTask?.close({
success: () => {
console.log('ws关闭连接');
@@ -64,7 +67,55 @@
socketTask.onMessage((result) => {
messageHandler(JSON.parse(result.data))
})
+ //==================================
+ // 监听连接打开
+ socketTask.onOpen((res) => {
+ console.log('✅ WebSocket连接已建立')
+ // reconnectAttempts = 0 // 连接成功后重置重连次数
+ // 可以在这里发送心跳或订阅消息
+ // startHeartbeat()
+ })
+ // 监听连接关闭
+ socketTask.onClose((res) => {
+ console.log(`WebSocket连接关闭,代码: ${res.code}, 原因: ${res.reason}`)
+ startHeartbeat()
+ // 根据不同的关闭代码处理
+ if (res.code === 1000) { // 正常关闭
+ console.log('连接正常关闭')
+ } else if (res.code === 1006) { // 异常关闭
+ console.log('连接异常关闭,尝试重连...')
+ } else if (res.code === 1011) { // 服务器内部错误
+ console.log('服务器内部错误(1011),延迟重连...')
+ } else {
+ console.log('其他原因关闭,尝试重连...')
+ }
+ })
+
+ // 监听错误
+ socketTask.onError((err) => {
+ console.error('WebSocket发生错误:', err)
+ })
}
+ 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})
}
--
Gitblit v1.9.3