data(){
return{
// websocket
ws: {},
wsUrl: 'wss://jhsy.linkcloud360.com/ws',
heart_jump: false, //websocket 心跳状态
ws_heart: '', // ws心跳定时器
//websocket持续连接的定时器
continuous_link: null,
}
}
created() {
// //页面刚进入时开启长连接
this.creat_socket(this.wsUrl);
},
destroyed() {
},
methods: {
// WebSjocket操作
creat_socket(url) {
this.ws = new WebSocket(url);
this.close_heart();
this.initWebSocket();
},
initWebSocket() {
let that = this;
let ws = that.ws;
// 打开WebSjocket
ws.onopen = function (e) {
console.log("WebSjocket已经打开");
that.heart_jump = true; // 心跳状态打开
that.heart();
// 再次清除防止重复请求
clearInterval(that.continuous_link);
};
// 接收WebSjocket
// let mouse_over = [];
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关闭");
};
// 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);
},
}
WebSocket心跳机制
最新推荐文章于 2024-10-09 20:41:09 发布