| | |
| | | this.ws = new WebSocket(this.wsUrl); |
| | | this.ws.onopen = () => { |
| | | this.status = 'open'; |
| | | this.heartCheck(); |
| | | if (data) { this.ws.send(data) } |
| | | }; |
| | | |
| | | this.ws.onmessage = e => { |
| | | if (e.data === 'pong') { |
| | | this.pingPong = 'pong' |
| | | } else { |
| | | this.msgCallback(JSON.parse(e.data)); |
| | | } |
| | | this.msgCallback(JSON.parse(e.data)); |
| | | }; |
| | | |
| | | this.ws.onclose = () => { |
| | | clearInterval(this.pingInterval); |
| | | clearInterval(this.pongInterval) |
| | | if (this.status === 'close') { |
| | | //console.log(‘手动关闭成功‘,new Date()) |
| | | } else { |
| | |
| | | return false |
| | | } |
| | | |
| | | heartCheck() {// 心跳 |
| | | this.pingPong = 'ping'; |
| | | let timer = this.time + 1000 |
| | | this.pingInterval = setInterval(() => { |
| | | if (this.ws.readyState === 1) { |
| | | this.ws.send('ping') |
| | | } |
| | | }, this.time); |
| | | this.pongInterval = setInterval(() => { |
| | | if (this.pingPong === 'ping') { |
| | | clearInterval(this.pingInterval); |
| | | clearInterval(this.pongInterval) |
| | | this.ws.close() |
| | | } else { |
| | | this.pingPong = 'ping' |
| | | } |
| | | }, timer) |
| | | } |
| | | |
| | | sendHandle(data) { |
| | | return this.ws.send(data); |
| | | } |
| | | |
| | | relink() { |
| | | if (this.status == 'open' && this.readyState == 1) { //连接正常 |
| | | if (this.status == 'open') { //连接正常 |
| | | return |
| | | } |
| | | if (this.initTimeOut) { //定时器已经启动 |
| | | return; |
| | | } |
| | | this.initTimeOut = setTimeout(() => { |
| | | clearInterval(this.pingInterval); |
| | | clearInterval(this.pongInterval); |
| | | this.initTimeOut = null; |
| | | this.init(); |
| | | }, this.initTime) |