var ws;//websocket实例 var heartCheck; var lockReconnect = false;//避免重复连接 var wsUrl = "ws://116.62.207.100:8080/websocket"; function createWebSocket(url) { try { ws = new WebSocket(url); initEventHandle(); } catch (e) { reconnect(url); } } function initEventHandle() { ws.onclose = function () { console.log("webscoket关闭状态即将重连...") reconnect(wsUrl); }; ws.onerror = function () { console.log("webscoket异常状态即将重连...") reconnect(wsUrl); }; ws.onopen = function () { console.log("webscoket已经链接 心跳检测重置中...") //心跳检测重置 heartCheck.reset().start(); }; ws.onmessage = function (event) { console.log("【收到】:" + event.data); //如果获取到消息,心跳检测重置 //拿到任何消息都说明当前连接是正常的 heartCheck.reset().start(); } } function reconnect(url) { if(lockReconnect) return; lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 setTimeout(function () { createWebSocket(url); lockReconnect = false; }, 2000); } //心跳检测 heartCheck = { timeout: 90000,//90秒 timeoutObj: null, serverTimeoutObj: null, reset: function(){ clearTimeout(this.timeoutObj); clearTimeout(this.serverTimeoutObj); return this; }, start: function(){ var self = this; //这里发送一个心跳,后端收到后,返回一个心跳消息, //onmessage拿到返回的心跳就说明连接正常 send("HeadBeat"); this.timeoutObj = setTimeout(function(){ console.log("【走到这一步的原因很简单,因为你没有收到心跳消息,那么N秒后将自动关闭重连】") self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了 ws.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次 }, self.timeout) }, this.timeout) } } createWebSocket(wsUrl); //WebSocket发送请求 function send(message) { if (!window.WebSocket) { return; } if (ws.readyState == WebSocket.OPEN) { console.log('【发送】:'+JSON.stringify(message)) ws.send(JSON.stringify(message)); } else { layui.use('layer', function(){ var layer = layui.layer; layer.msg('您还未连接上服务器,请刷新页面重试!',{icon: 0}); }) } } |
|