<template></template>
<script>
import { sysBaseUrl } from "@/config/sysServe";
export default {
data() {
return {
maxReconnect: 3, // 最大重连次数,-1代表无限重连
reconnectTime: 0, // 重连尝试次数
socket: "",
lockReconnect: false,
timer: null,
heartbeat: null,
heartbeatTimeOut: null,
url: "",
};
},
methods: {
destroyedWs() {
// 关闭使用close方法关闭socket
this.socket && this.socket.close();
// 清除定时器
this.timer && clearInterval(this.timer);
this.heartbeat && clearTimeout(this.heartbeat);
this.heartbeatTimeOut && clearTimeout(this.heartbeatTimeOut);
},
init() {
this.url = "ws://" + sysBaseUrl + "/deli/imserver/" + "10";
this.initWebSocket();
},
// 初始化WebSocket
initWebSocket() {
if (typeof WebSocket === "undefined") {
this.$message.error("您的浏览器不支持WebSocket");
} else {
const url = this.url;
// 实例化socket
this.socket = new WebSocket(url);
// 监听socket连接
this.socket.onopen = this.open;
// 监听socket错误信息
this.socket.onerror = this.error;
// 监听socket消息
this.socket.onmessage = this.getMessage;
// 连接关闭
this.socket.onclose = this.close;
}
},
open: function () {
//开启心跳
this.startHeartbeat();
},
error: function () {
this.$message.error("WebSocket连接错误");
//重连
this.reconnect();
},
getMessage: function (msg) {
console.log(msg, 61);
const text = msg.data;
// //收到服务器信息,心跳重置并发送
this.startHeartbeat();
if (text.indexOf("ping") > 0) {
return;
}
// /* 连接成功的推送提示消息 */
if (text === "连接成功") {
// this.$message.success("WebSocket连接成功");
this.$emit("Loading", false);
return;
}
this.$emit("getMessage", text);
},
send: function (params) {
this.socket.send(params);
},
close: function () {
// this.$message.warning("socket已经关闭");
},
/**
* 重新连接(无限重连)
*/
reconnect() {
if (this.socket.readyState === 1) {
// 如果状态等于1代表 websocket连接正常
return;
}
if (
this.lockReconnect ||
(this.maxReconnect !== -1 && this.reconnectTime >= this.maxReconnect)
) {
return;
}
// 让重连锁变为true,阻止进入下一个循环
this.lockReconnect = true;
setTimeout(() => {
this.reconnectTime++;
// 建立新连接
this.initWebSocket();
this.lockReconnect = false;
}, 5000);
},
/**
* 开启心跳
*/
startHeartbeat() {
const webSocket = this.socket;
// 清空定时器
this.heartbeat && clearTimeout(this.heartbeat);
// 延时发送下一次心跳
this.heartbeat = setTimeout(() => {
/* 状态失败重连 */
if (webSocket.readyState !== 1) {
this.reconnect();
}
// 心跳间隔时间是30s
}, 30 * 1000);
},
},
};
</script>
<style></style>
09-13