Websocket 相关 发表于 2019-01-01 | 分类于 Websocket 心跳包 - 断线重连123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899// 避免重复连接let lockReconnect = false;let ws = null;let wsUrl = '192.168.50.37:8181';createWebSocket(wsUrl);// 建立websocket连接function createWebSocket() { try { ws = new WebSocket('ws://' + wsUrl); initEventHandle(); } catch (e) { reconnect(wsUrl); }}// 重连function reconnect() { if (lockReconnect) { return; } lockReconnect = true; setTimeout(function () { createWebSocket(wsUrl); console.log('正在重连,当前时间:' + new Date()); lockReconnect = false; }, 3000);}// 初始化function initEventHandle() { // 连接成功后 ws.onopen = function() { console.log('连接成功'); // 心跳检测重置 heartCheck.reset(); }; // 收到消息后 ws.onmessage = function(e) { // 心跳检测重置 heartCheck.reset(); let data = JSON.parse(e.data); switch (data.req_type) { case 'beat': console.log('心跳检测成功,当前时间:' + new Date()); break; case 'login': console.log('SERVER:' + data.body.time); break; default: break; } }; // 连接关闭后 ws.onclose = function() { console.log('关闭连接'); reconnect(wsUrl); }; ws.onerror = function () { reconnect(); };}// 心跳检测let heartCheck = { timeout: 15000, timeoutObj: null, serverTimeoutObj: null, reset: function(){ clearTimeout(this.timeoutObj); clearTimeout(this.serverTimeoutObj); this.start(); }, start: function(){ let self = this; this.timeoutObj = setTimeout(function(){ let heartData = { req_type: 'beat', req_id: new Date().getTime(), body: [], }; ws.send(JSON.stringify(heartData)); // 发送心跳包 console.log('发送心跳包,当前时间:' + new Date()); // 如果超过一定时间还没重置,说明后端主动断开了 self.serverTimeoutObj = setTimeout(function() { ws.close(); }, self.timeout); }, this.timeout) }}; 参考资料 初探和实现websocket心跳重连(npm: websocket-heartbeat-js) 本文作者:Mr 本文链接: http://sevming.github.io/Websocket/websocket.html 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!