在使用websocket的时候,遇到了一个websocket在链接一段时间就异常断开链接了。第一想法就是从新去链接websocket(websock.onopen),后来发现这种方式是错误的,查阅文档发现,要想从新创建链接,就须要一种心跳思想去处理(实时监听链接状况,断了就去重连)
下面以Vue代码为准:web
let lockReconnect = false;//避免重复链接 let wsUrl = '‘ // url; let ws; let tt; createWebSocket() { let that = this; try { ws = new WebSocket(wsUrl); this.init(); } catch(e) { console.log('catch'); that.reconnect(wsUrl); } }, init() { let that = this; //心跳检测 let heartCheck = { timeout: 3000, timeoutObj: null, serverTimeoutObj: null, start: function(){ console.log('start'); let self = this; this.timeoutObj && clearTimeout(this.timeoutObj); this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj); this.timeoutObj = setTimeout(function(){ //这里发送一个心跳,后端收到后,返回一个心跳消息, console.log('55555'); ws.send("888"); self.serverTimeoutObj = setTimeout(function() { console.log(111); console.log(ws); ws.close(); // createWebSocket(); }, self.timeout); }, this.timeout) } }; ws.onclose = function () { console.log('连接关闭'); that.reconnect(wsUrl); location.reload() }; ws.onerror = function() { console.log('发生异常了'); that.reconnect(wsUrl); location.reload(); }; ws.onopen = function () { //心跳检测重置 heartCheck.start(); }; ws.onmessage = function (e) { //拿到任何消息都说明当前链接是正常的 console.log('接收到消息'); console.log(e); heartCheck.start(); } }, reconnect(url) { if(lockReconnect) { return; } lockReconnect = true; //没链接上会一直重连,设置延迟避免请求过多 tt && clearTimeout(tt); tt = setTimeout( () => { this.createWebSocket(url); lockReconnect = false; }, 4000); }, this.createWebSocket(wsUrl);