在vue中,websocket实现消息推送通知
data() {
return {
websocket: null,
timeout: 30 * 1000,
timeoutObj: null,
serverTimeoutObj: null,
timeoutnum: null,
}
}
- 初始化websocket对象
initWebSocket() {
let url = "wss://你与后端规定好的通信地址";
this.websocket = new WebSocket('你与后端规定好的通信地址');
this.websocket.onerror = (error) => {
console.error("WebSocket error:", error);
this.reconnect();
};
this.websocket.onopen = () => {
console.log("WebSocket连接已建立");
this.reset().start();
};
this.websocket.onmessage = this.setOnmessageMessage;
this.websocket.onclose = () => {
this.reconnect()
console.log("WebSocket连接已关闭");
};
window.onbeforeunload = () => {
this.websocket.close()
}
}
- 在初始化中使用到的方法
setOnmessageMessage(event) {
const message = event.data;
if (message && message == "pong") {
this.reset().start()
}else {
if(message && message == 'refresh') {
}
}
console.log("Received message:", message);
},
reconnect() {
if (this.lockReconnect) return;
this.lockReconnect = true;
this.timeoutnum && clearTimeout(this.timeoutnum);
this.timeoutnum = setTimeout(() => {
this.initWebSocket();
this.lockReconnect = false;
}, 5000);
},
reset() {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this
},
start() {
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(() => {
this.websocket.send("ping");
console.log("发送心跳检测");
this.serverTimeoutObj = setTimeout(() => {
console.log("未收到心跳检测回复");
this.websocket.close()
}, this.timeout)
}, this.timeout);
},
- 调用初始化websocket对象的方法
mounted() {
this.initWebSocket();
}