1、WebSocket链接中断原因
WebSocket断开的原因有很多,最好在WebSocket断开时,将错误打印出来。文章来源:https://www.toymoban.com/news/detail-601751.html
const Wsurl = `${process.env.VUE_APP_WEBSOCKET_BASE_URL}/${sessionStorage.getItem('userId')}`
this.ws = new WebSocket(Wsurl);
this.ws.onclose = function (e) {
console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
};
二、心跳机制防止自动断开
WebSocket在一段时间内没有进行通讯便会自读断开链接,可以每隔30秒或一分钟向服务器发送一次通讯防止链接终端文章来源地址https://www.toymoban.com/news/detail-601751.html
data() {
return {
lockReconnect: false,
ws: null,
}
},
methods: {
join() {
const Wsurl = `后端WebSocket接口URl`
this.ws = new WebSocket(Wsurl);
const self = this;
this.ws.onopen = function (event) {
console.log('已经打开连接');
//心跳检测重置
self.heartCheckReset()
self.heartCheckStart()
self.text_content = self.text_content + "已经打开连接!" + "\n";
};
this.ws.onmessage = function (event) {
self.heartCheckReset()
self.heartCheckStart()
self.text_content = event.data + "\n";
if (event.data == 'ping' || event.data == '连接成功') return ''
console.log(event);
self.getNoticeList()
};
this.ws.onclose = function (event) {
console.log('关闭');
console.log(event, '关闭');
self.reconnect()
self.text_content = self.text_content + "已经关闭连接!" + "\n";
};
},
//若链接中断30秒后创建新的链接
reconnect() {
if (this.lockReconnect) return ''
this.lockReconnect = true
setTimeout(() => {
this.join()
this.lockReconnect = false
//若链接中断30秒后创建新的链接
}, 30000)
},
//清空定时器
heartCheckReset() {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
},
// 开启定时器
heartCheckStart() {
var self = this;
this.timeoutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
self.ws.send("ping");
console.log("ping!")
self.serverTimeoutObj = setTimeout(function () { //如果超过一定时间还没重置,说明后端主动断开了
self.ws.close();
},30000 )
}, 30000)
},
}
到了这里,关于Vue中WebSocket链接中断、心跳机制防止自动断开的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!