From af168b96d839ce7d4332ac972b16548d5d442f9b Mon Sep 17 00:00:00 2001 From: piratecaptain37 <132531339+piratecaptain37@users.noreply.github.com> Date: Wed, 22 Apr 2026 15:41:41 +0800 Subject: [PATCH] =?UTF-8?q?websocket=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.development | 2 +- src/utils/ws.js | 24 ++++++++++++++++++++++-- src/views/index.vue | 9 +++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/.env.development b/.env.development index 01bce7c..f045ce7 100644 --- a/.env.development +++ b/.env.development @@ -4,4 +4,4 @@ VITE_APP_TITLE = 智汇管理系统 VITE_APP_ENV = 'development' # 智汇管理系统/开发环境 -VITE_APP_BASE_API = 'http://192.168.1.5:8081' +VITE_APP_BASE_API = 'http://192.168.1.6:8081' diff --git a/src/utils/ws.js b/src/utils/ws.js index a09c6cf..47e2e45 100644 --- a/src/utils/ws.js +++ b/src/utils/ws.js @@ -32,6 +32,7 @@ function buildWsUrl() { } export function connectWs(onMessage) { + console.trace('connectWs called') if (!getToken()) { console.warn('[WebSocket] missing token') return @@ -73,10 +74,20 @@ export function connectWs(onMessage) { }) } - ws.onclose = () => { - console.log('[WebSocket] closed') + ws.onclose = (event) => { + console.log('[WebSocket] closed', { code: event.code, reason: event.reason }) ws = null + if (isNonRetryableClose(event)) { + console.warn('[WebSocket] stop reconnect because close reason is not retryable', { + code: event.code, + reason: event.reason + }) + retryCount = 0 + clearReconnectTimer() + return + } + if (!manualClose && subscribers.size > 0) { reconnectTimer = setTimeout(() => { console.log('[WebSocket] reconnecting') @@ -153,3 +164,12 @@ function clearReconnectTimer() { reconnectTimer = null } } + +function isNonRetryableClose(event) { + const reason = (event?.reason || '').toLowerCase() + return ( + reason.includes('invalid token') || + reason.includes('missing token') || + reason.includes('deptid is null') + ) +} diff --git a/src/views/index.vue b/src/views/index.vue index 14f7573..753b6eb 100644 --- a/src/views/index.vue +++ b/src/views/index.vue @@ -184,6 +184,7 @@ import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue' import { useRouter } from 'vue-router' import { closeWs, connectWs } from '@/utils/ws' +import { getToken } from '@/utils/auth' import { getHomeAlarmStat, getHomeAlarmTrend, @@ -752,6 +753,14 @@ function pushRealtimeAlarm(event) { onMounted(() => { loadHomeData() + + const token = getToken() + + if (!token || token === 'undefined' || token === 'null' || token.length < 30) { + console.warn('[Home] token无效,不连接WebSocket') + return + } + connectWs(handleWsMessage) })