websocket优化

This commit is contained in:
piratecaptain37
2026-04-22 15:41:41 +08:00
parent 43b8b8ad68
commit af168b96d8
3 changed files with 32 additions and 3 deletions

View File

@@ -4,4 +4,4 @@ VITE_APP_TITLE = 智汇管理系统
VITE_APP_ENV = 'development' VITE_APP_ENV = 'development'
# 智汇管理系统/开发环境 # 智汇管理系统/开发环境
VITE_APP_BASE_API = 'http://192.168.1.5:8081' VITE_APP_BASE_API = 'http://192.168.1.6:8081'

View File

@@ -32,6 +32,7 @@ function buildWsUrl() {
} }
export function connectWs(onMessage) { export function connectWs(onMessage) {
console.trace('connectWs called')
if (!getToken()) { if (!getToken()) {
console.warn('[WebSocket] missing token') console.warn('[WebSocket] missing token')
return return
@@ -73,10 +74,20 @@ export function connectWs(onMessage) {
}) })
} }
ws.onclose = () => { ws.onclose = (event) => {
console.log('[WebSocket] closed') console.log('[WebSocket] closed', { code: event.code, reason: event.reason })
ws = null 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) { if (!manualClose && subscribers.size > 0) {
reconnectTimer = setTimeout(() => { reconnectTimer = setTimeout(() => {
console.log('[WebSocket] reconnecting') console.log('[WebSocket] reconnecting')
@@ -153,3 +164,12 @@ function clearReconnectTimer() {
reconnectTimer = null reconnectTimer = null
} }
} }
function isNonRetryableClose(event) {
const reason = (event?.reason || '').toLowerCase()
return (
reason.includes('invalid token') ||
reason.includes('missing token') ||
reason.includes('deptid is null')
)
}

View File

@@ -184,6 +184,7 @@
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue' import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { closeWs, connectWs } from '@/utils/ws' import { closeWs, connectWs } from '@/utils/ws'
import { getToken } from '@/utils/auth'
import { import {
getHomeAlarmStat, getHomeAlarmStat,
getHomeAlarmTrend, getHomeAlarmTrend,
@@ -752,6 +753,14 @@ function pushRealtimeAlarm(event) {
onMounted(() => { onMounted(() => {
loadHomeData() loadHomeData()
const token = getToken()
if (!token || token === 'undefined' || token === 'null' || token.length < 30) {
console.warn('[Home] token无效不连接WebSocket')
return
}
connectWs(handleWsMessage) connectWs(handleWsMessage)
}) })