<script>
const heartCheck = {
timeout: 6 * 1000,
timer: null,
serverTimer: null,
reset() {
this.timer && clearTimeout(this.timer);
this.serverTimer && clearTimeout(this.serverTimer);
},
start(ws, params = "ping") {
this.reset();
this.timer = setTimeout(() => {
ws.send(params);
this.serverTimer = setTimeout(() => {
ws.close();
}, this.timeout);
}, this.timeout);
},
};
export default {
data() {
let origin = window.location.origin;
if (process.env.NODE_ENV == "production") {
origin = window.location.origin;
}
let wsuri = (origin + "/ws/").replace("http", "ws");
return {
wsuri,
lockReconnect: false,
maxReconnect: 10,
socket: null,
queryParams: "ping",
userId:""
}
},
mounted() {
this.initWebSocket();
window.addEventListener("beforeunload", (e) => this.beforeunloadHandler(e));
},
beforeDestroy() {
this.beforeunloadHandler();
setTimeout(() => {
this.$destroy();
}, 1000);
window.removeEventListener("beforeunload", (e) =>
this.beforeunloadHandler(e)
);
},
methods: {
beforeunloadHandler() {
heartCheck.reset();
this.lockReconnect = false;
this.socket && this.socket.close();
console.log("关闭websoket");
},
initWebSocket() {
try {
if ("WebSocket" in window) {
this.socket = new WebSocket(this.wsuri + this.userId);
} else {
this.$message.error("您的浏览器不支持websocket");
console.log("您的浏览器不支持websocket");
}
this.socket.onopen = this.websocketonopen;
this.socket.onmessage = this.websocketonmessage;
this.socket.onclose = this.websocketclose;
this.socket.onerror = this.websocketonerror;
} catch (e) {
console.error("e: ", e);
}
},
websocketonopen() {
console.log("WebSocket连接成功", this.socket.readyState);
this.maxReconnect = 10;
heartCheck.start(this.socket, this.queryParams);
this.websocketsend();
},
websocketsend() {
this.socket.send(this.queryParams);
},
websocketonmessage(e) {
try {
heartCheck.start(this.socket, this.queryParams);
if (e.data !== "pong") {
let msg = JSON.parse(e.data);
console.log(msg, "收到消息");
}
} catch (e) {
console.error("e: ", e);
}
},
websocketclose(e) {
console.log("connection closed (" + e.code + ")");
this.reconnect();
},
websocketonerror(e) {
console.log("WebSocket连接发生错误", e);
this.reconnect();
},
reconnect() {
console.log("尝试重连");
this.socket && this.socket.close();
if (this.lockReconnect || this.maxReconnect <= 0) return;
console.log("连接中");
setTimeout(() => {
this.maxReconnect--;
this.initWebSocket();
}, 6 * 1000);
},
}
</script>