| | |
| | | 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() |
| | |
| | | function messageHandler(payload) { |
| | | switch (payload.biz_code) { |
| | | case 'JOB_ISREFRESH': |
| | | appStore.setJobUpdateKeyAdd() |
| | | break |
| | | case 'DEVICE_ISREFRESH': |
| | | appStore.setDeviceUpdateKeyAdd() |
| | | break |
| | | case 'DOWNLOAD_PROGRESS': |
| | | break |
| | |
| | | url: '/pages/login/index' |
| | | }) |
| | | break |
| | | case 'VoiceCall': |
| | | enterRoom(payload, userId.value) |
| | | break |
| | | default: |
| | | break; |
| | | } |
| | |
| | | |
| | | // 关闭ws |
| | | function closeWS() { |
| | | stopHeartbeat() |
| | | socketTask?.close({ |
| | | success: () => { |
| | | console.log('ws关闭连接'); |
| | |
| | | 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}) |
| | | } |