refactor(WebSocket): 优化心跳机制与错误处理逻辑

This commit is contained in:
yangzhe 2025-12-11 16:15:27 +08:00
parent cfd0d0f0f2
commit f557d658e7
1 changed files with 28 additions and 26 deletions

54
App.vue
View File

@ -10,7 +10,7 @@ export default {
// WebSocket // WebSocket
ws: null, // WebSocket ws: null, // WebSocket
lockReconnect: false, // lockReconnect: false, //
timeout: 30000, // // timeout: 30000, //
timeoutObj: null, // timeoutObj: null, //
serverTimeoutObj: null, // serverTimeoutObj: null, //
timeoutnum: null, // timeoutnum: null, //
@ -114,32 +114,29 @@ export default {
// //
start() { start() {
this.timeoutObj = setTimeout(() => { this.timeoutObj = setTimeout(() => {
try { //
if ( if (
this.ws && this.ws &&
this.ws.readyState === 1 && this.ws.readyState === 1 &&
this.vuex_user && this.vuex_user &&
(this.vuex_user.id || this.vuex_user.Id) (this.vuex_user.Id || this.vuex_user.id)
) { ) {
this.ws.send("heartCheck"); //
} else { this.ws.send("heartCheck");
this.lockReconnect = false; } else {
this.reconnect(); //
}
} catch (err) {
this.lockReconnect = false; this.lockReconnect = false;
this.reconnect(); this.reconnect();
} }
// //
this.serverTimeoutObj = setTimeout(() => { this.serverTimeoutObj = setTimeout(() => {
try { // console.log("[WebSocket] ");
this.ws && this.ws.close(); this.ws && this.ws.close();
} catch (e) {}
this.lockReconnect = false; this.lockReconnect = false;
this.reconnect(); this.reconnect();
}, this.timeout); }, 30000);
}, this.timeout); }, 30000);
}, },
// //
handleWsOpen() { handleWsOpen() {
@ -153,10 +150,12 @@ export default {
// //
this.reset(); this.reset();
console.log("[WebSocket] 收到消息:", e);
// //
if (typeof e.data === "string" && e.data.indexOf("heartCheck") >= 0) { // if (typeof e.data === "string" && e.data.indexOf("heartCheck") >= 0) {
return; // return;
} // }
// JSON oa-web-phone { Type, Data } // JSON oa-web-phone { Type, Data }
let msgData = null; let msgData = null;
@ -169,6 +168,10 @@ export default {
const type = msgData.Type; const type = msgData.Type;
console.log("收到消息类型:", type);
//
if (type === "pong") return;
// 退 // 退
if (type === "Exit") { if (type === "Exit") {
try { try {
@ -209,14 +212,13 @@ export default {
}, },
// //
handleWsClose(e) { handleWsClose(e) {
console.log(`[WebSocket] 连接关闭: code=${e.code}, reason=${e.reason}`); // console.log(`[WebSocket] : code=${e.code}, reason=${e.reason}`);
this.lockReconnect = false; this.lockReconnect = false;
this.reconnect(); this.reconnect();
}, },
// //
handleWsError(e) { handleWsError(e) {
console.log("[WebSocket] 连接错误:", e); // console.log("[WebSocket] :", e);
this.lockReconnect = false; this.lockReconnect = false;
this.reconnect(); this.reconnect();
}, },
@ -237,7 +239,7 @@ export default {
}, },
mounted() { mounted() {
// 使 oa-web-phone WebSocket // 使 oa-web-phone WebSocket
// this.startLink(); // 线 this.startLink(); // 线
}, },
}; };
</script> </script>