. 1 function longSock (URL, Fn, Intro = '' ) { 2 the let = lockReconnect to false // avoid repeated connections . 3 the let = timeoutFlag to true . 4 the let timeoutSet = null . 5 the let reconectNum = 0 . 6 const timeout = 30000 // timeout interval reconnection . 7 the let WS . 8 function reconnect () { . 9 IF (lockReconnect) return 10 lockReconnect = to true . 11 // the connection will not reconnect, the delay provided to avoid excessive request 12 is IF (reconectNum <. 3 ) { 13 is the setTimeout ( function () { 14 timeoutFlag = to true 15 createWebSocket () 16 console.info (Intro `$ {} is the first re-connection reconectNum +. 1 {$ } times`) . 17 reconectNum ++ 18 is lockReconnect = to false . 19 }, 5000) / / provided here reconnect spaced (MS) 20 is } 21 is } 22 is // heartbeat detector 23 is const heartCheck = { 24 timeout: 5000, // ms 25 timeoutObj: null , 26 is serverTimeoutObj: null, 27 reset: function() { 28 clearInterval(this.timeoutObj) 29 clearTimeout(this.serverTimeoutObj) 30 return this 31 }, 32 start: function() { 33 const self = this 34 let count = 0 35 this.timeoutObj = setInterval(() => { 36 if (count < 3) { 37 if (ws.readyState === 1) { 38 ws.send('HeartBeat') 39 console.info(`${intro}HeartBeat第${count + 1}次`) 40 } 41 count++ 42 } else { 43 clearInterval(this.timeoutObj) 44 count = 0 45 if (ws.readyState === 0 && ws.readyState === 1) { 46 ws.close() 47 } 48 } 49 }, self.timeout) 50 } 51 } 52 const createWebSocket = () => { 53 console.info(`${intro}创建11`) 54 timeoutSet = setTimeout(() => { 55 if (timeoutFlag && reconectNum < 3) { 56 console.info(`${intro}重连22`) 57 reconectNum++ 58 createWebSocket() 59 } 60 }, timeout) 61 ws = new WebSocket(url) 62 63 ws.onopen = () => { 64 reconectNum = 0 65 timeoutFlag = false 66 clearTimeout(timeoutSet) 67 heartCheck.reset().start() 68 } 69 ws.onmessage = evt => { 70 heartCheck.reset().start() 71 // console.info(evt); 72 if(evt.data === 'HeartBeat') return 73 fn(evt, ws) 74 } 75 ws.onclose = e => { 76 console.info(`${intro}关闭11`, e.code) 77 if (e.code !== 1000) { 78 timeoutFlag = false 79 clearTimeout(timeoutSet) 80 reconnect() 81 } else { 82 clearInterval(heartCheck.timeoutObj) 83 clearTimeout(heartCheck.serverTimeoutObj) 84 } 85 } 86 ws.onerror = function() { 87 console.info(`${intro}错误11`) 88 reconnect() //重连 89 } 90 } 91 createWebSocket() 92 return ws 93 } 94 export default longSock
1 // method call 2 const = Handler (EVT, WS) => { . 3 // EVT is websockett data . 4 // WS request name is easy to close WebSocket . 5 } . 6 . 7 const = wssCenter the createSocket (WSS `: // URL `, handler, 'reception center - small card') . 8 . 9 10 . 11 wssCenter.close (); // disconnect