<script>
export default {
data() {
return {
websock: null,
timer: "",
startTime: "",
endTime: "",
}
},
created() {
clearInterval(this.timer);
this.timer = setInterval(() => {
this.initWebSocket();
}, 1000);
},
destroyed() {
this.websock.close(); //离开路由之后断开websocket连接
},
methods: {
initWebSocket() {
//初始化weosocket
const wsuri = "ws://xxxxxxxxxxxx.com:2323/12";
this.websock = new WebSocket(wsuri);
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},
websocketonopen() {
//连接建立之后执行send方法发送数据
clearInterval(this.timer);
this.heartbeat();
},
websocketonerror() {
//连接建立失败重连
this.initWebSocket();
},
websocketonmessage(e) {
// websocket返回的数据
console.log(e.data)
},
websocketsend(Data) {
//数据发送
this.websock.send(Data);
},
websocketclose(e) {
//关闭
console.log("断开连接", e);
},
heartbeat() {
clearInterval(this.timer);
this.timer = setInterval(() => {
if (this.endTime != "") {
if (this.startTime - this.endTime >= 5000) {
console.log("重新链接!");
this.initWebSocket();
this.endTime = "";
this.startTime = "";
}
}
this.startTime = Date.parse(new Date());
if (this.startTime - this.endTime <= 5000 || this.endTime == "") {
// 根据后端看你看什么样的数据包作为心跳
this.websocketsend("{'msg':'heartbeat'}");
}
}, 1000);
}
}
}
</script>
|