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

38
App.vue
View File

@ -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.vuex_user.Id || this.vuex_user.id)
) {
//
this.ws.send("heartCheck");
} else {
this.lockReconnect = false;
this.reconnect();
}
} catch (err) {
//
this.lockReconnect = false;
this.reconnect();
}
//
this.serverTimeoutObj = setTimeout(() => {
try {
// console.log("[WebSocket] ");
this.ws && this.ws.close();
} catch (e) {}
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(); // 线
},
};
</script>