data(){
return{
ws: {},
wsUrl: 'wss://jhsy.linkcloud360.com/ws',
heart_jump: false,
ws_heart: '',
continuous_link: null,
}
}
created() {
this.creat_socket(this.wsUrl);
},
destroyed() {
},
methods: {
creat_socket(url) {
this.ws = new WebSocket(url);
this.close_heart();
this.initWebSocket();
},
initWebSocket() {
let that = this;
let ws = that.ws;
ws.onopen = function (e) {
console.log("WebSjocket已经打开");
that.heart_jump = true;
that.heart();
clearInterval(that.continuous_link);
};
ws.onmessage = function (event) {
console.log("接收WebSjocket", event);
if ((!event && !event.data) || event.data == "undefined") {
return;
} else {
let data = event.data
}
}
ws.onclose = function (e) {
if (that.heart_jump) {
that.close_heart();
that.heart_jump = false;
}
console.log("WebSocket关闭");
};
ws.onerror = function (e) {
if (that.heart_jump) {
that.close_heart();
that.heart_jump = false;
}
that.reconnect(that.wsUrl);
console.log("WebSocket发生错误");
};
},
heart(props) {
let that = this;
this.ws_heart = setInterval(() => {
that.ws.send(props);
}, 10 * 1000);
},
close_heart() {
console.log("ws心跳结束");
clearInterval(this.ws_heart);
this.ws_heart = null;
},
reconnect(url) {
if (this.lockReconnect) return;
this.lockReconnect = true;
let that = this;
clearInterval(this.continuous_link);
this.continuous_link = setInterval(function () {
that.lockReconnect = false;
that.creat_socket(url);
console.log("重启中...");
}, 5000);
},
}