1、WebSocket链接中断原因 WebSocket断开的原因有很多,最好在WebSocket断开时,将错误打印出来。

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秒或一分钟向服务器发送一次通讯防止链接终端

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)

},

}

精彩文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。