From f557d658e706d210178d3b17ed9e622bf88253da Mon Sep 17 00:00:00 2001 From: yangzhe Date: Thu, 11 Dec 2025 16:15:27 +0800 Subject: [PATCH] =?UTF-8?q?refactor(WebSocket):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=BF=83=E8=B7=B3=E6=9C=BA=E5=88=B6=E4=B8=8E=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App.vue | 54 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/App.vue b/App.vue index c94eace..c908181 100644 --- a/App.vue +++ b/App.vue @@ -10,7 +10,7 @@ export default { // WebSocket 实例与连接控制 ws: null, // 当前 WebSocket 连接 lockReconnect: false, // 是否处于稳定连接,防止重复重连 - timeout: 30000, // 心跳间隔(毫秒) + // timeout: 30000, // 心跳间隔(毫秒) timeoutObj: null, // 心跳倒计时定时器 serverTimeoutObj: null, // 心跳响应等待定时器 timeoutnum: null, // 重连延时定时器 @@ -114,32 +114,29 @@ export default { // 启动心跳与超时处理 start() { this.timeoutObj = setTimeout(() => { - try { - if ( - this.ws && - this.ws.readyState === 1 && - this.vuex_user && - (this.vuex_user.id || this.vuex_user.Id) - ) { - this.ws.send("heartCheck"); - } else { - this.lockReconnect = false; - this.reconnect(); - } - } catch (err) { + //这里发送一个心跳,后端收到后,返回一个心跳消息 + if ( + this.ws && + this.ws.readyState === 1 && + this.vuex_user && + (this.vuex_user.Id || this.vuex_user.id) + ) { + //如果连接正常 + this.ws.send("heartCheck"); + } else { + //否则重连 this.lockReconnect = false; this.reconnect(); } // 心跳发送后等待后端响应,超时则断开重连 this.serverTimeoutObj = setTimeout(() => { - try { - this.ws && this.ws.close(); - } catch (e) {} + // console.log("[WebSocket] 心跳响应超时,断开重连"); + this.ws && this.ws.close(); this.lockReconnect = false; this.reconnect(); - }, this.timeout); - }, this.timeout); + }, 30000); + }, 30000); }, // 连接成功 handleWsOpen() { @@ -153,10 +150,12 @@ export default { // 收到任何消息都重置心跳 this.reset(); + console.log("[WebSocket] 收到消息:", e); + // 心跳消息不处理 - if (typeof e.data === "string" && e.data.indexOf("heartCheck") >= 0) { - return; - } + // if (typeof e.data === "string" && e.data.indexOf("heartCheck") >= 0) { + // return; + // } // 尝试解析为 JSON(与 oa-web-phone 保持一致的结构:{ Type, Data }) let msgData = null; @@ -169,6 +168,10 @@ export default { const type = msgData.Type; + console.log("收到消息类型:", type); + // 收到服务端心跳响应不处理 + if (type === "pong") return; + // 退出登录通知 if (type === "Exit") { try { @@ -209,14 +212,13 @@ export default { }, // 连接关闭 handleWsClose(e) { - console.log(`[WebSocket] 连接关闭: code=${e.code}, reason=${e.reason}`); + // console.log(`[WebSocket] 连接关闭: code=${e.code}, reason=${e.reason}`); this.lockReconnect = false; this.reconnect(); }, // 连接错误 handleWsError(e) { - console.log("[WebSocket] 连接错误:", e); - + // console.log("[WebSocket] 连接错误:", e); this.lockReconnect = false; this.reconnect(); }, @@ -237,7 +239,7 @@ export default { }, mounted() { // 使用与 oa-web-phone 相同的原生 WebSocket 通信方式 - // this.startLink(); // 现在一直断线重连,先注释 + this.startLink(); // 现在一直断线重连,先注释 }, };