| const ws = new WebSocket('ws://ezlost') |
| |
| ws.onclose = () => reConnect() |
| ws.onerror = () => reConnect() |
| |
| ws.onmessage = () => { |
| |
| beatPack(ws, 5000).beat() |
| ... |
| } |
| |
| |
| function reConnect(){ |
| const _this = this |
| const connect = { |
| timer: null, |
| wait: 5000, |
| reconnect: function(){ |
| if(this.timer) return; |
| this.timer = setTimeout(() => { |
| _this.ws = new WebSocket('ws://ezlost') |
| clearTimeout(this.timer) |
| this.timer = null |
| }, this.wait); |
| } |
| } |
| connect.reconnect() |
| } |
| |
| |
| function beatPack(socketObj = {}, wait = 1000){ |
| return { |
| beatTimer: null, |
| closedTimer: null, |
| beat: function(){ |
| clearTimeout(this.beatTimer) |
| clearTimeout(this.closedTimer) |
| this.beatTimer = null |
| this.beatTimer = setTimeout(() => { |
| socketObj.readyState === 1 && socketObj.send('HEARTBEAT') |
| this.closedTimer = setTimeout(() => { |
| socketObj.close() |
| }, wait); |
| }, wait); |
| } |
| } |
| } |
| const ws = new WebSocket('ws://ezlost') |
| ws.onclose = () => reConnect(data) |
| ws.onerror = () => reConnect(data) |
| |
| |
| const postwsActions = { |
| '0': () => { ws.onopen = () => ws.send(data) }, |
| '1': () => ws.send(data), |
| } |
| postwsActions[ws.readyState] && postwsActions[ws.readyState]() |
| |
| |
| function reConnect(data){ |
| const _this = this |
| const connect = { |
| timer: null, |
| wait: 5000, |
| reconnect: function(){ |
| if(this.timer) return; |
| this.timer = setTimeout(() => { |
| _this.ws = new WebSocket('ws://ezlost') |
| _this.ws.onopen = () => ws.send(data) |
| clearTimeout(this.timer) |
| this.timer = null |
| }, this.wait); |
| } |
| } |
| connect.reconnect() |
| } |