1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| import store from '@/store';
export function WebSocketFunc(ws, wsUrl, callback, callback1) { var lockReconnect = false; function createWebSocket(url) { try { console.log('wsUrl', wsUrl); if ('WebSocket' in window) { ws = new WebSocket(url); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(url); } else { ws = new SockJS(url); } callback1 && callback1(ws); initEventHandle(); } catch (e) { reconnect(wsUrl); } }
function initEventHandle() { ws.onclose = function (evnt) { console.log( 'websocket 断开: ' + 'code:' + evnt.code + ' ' + 'reason:' + evnt.reason + ' ' + 'wasClean:' + evnt.wasClean ); if (store.state.websocket.isClose) { console.log('前端主动连接中断'); store.dispatch('websocket/getWsClose', false); } else { reconnect(evnt.target.url); console.log('心跳重连...'); } }; ws.onerror = function () { console.log('websocket服务出错了'); reconnect(wsUrl); }; ws.onopen = function () { console.log('send device sn: ', store.getters['user/curDevice'].sn); ws.send(store.getters['user/curDevice'].sn); heartCheck.reset().start(); }; ws.onmessage = function (evnt) { doWithMsg(evnt.data); heartCheck.reset().start(); };
function doWithMsg(msg) { console.log( "websocket's msg", msg.indexOf('成功建立websocket连接') == 0 || !msg.indexOf('Pong') || msg.indexOf('设备') != -1 || msg.indexOf('连接成功') != -1 ? msg : JSON.parse(msg) ); callback && callback(msg); } }
function reconnect(url) { console.log('正在重连...'); if (lockReconnect) return; lockReconnect = true; setTimeout(function () { createWebSocket(url); lockReconnect = false; }, 2000); }
var heartCheck = { timeout: 10000, timeoutObj: null, serverTimeoutObj: null, reset: function () { clearTimeout(this.timeoutObj); clearTimeout(this.serverTimeoutObj); return this; }, start: function () { var self = this; this.timeoutObj = setTimeout(function () { ws.send('Ping'); console.log('Ping'); self.serverTimeoutObj = setTimeout(function () { ws.close(); }, self.timeout); }, this.timeout); } };
createWebSocket(wsUrl); }
|