websocket保证可靠性实践

1,237 阅读1分钟

场景:项目中用websocket做一个简单的长连接,用来实时展示登录用户信息

代码如下:

对一些异常场景的测试:

1,服务器重启:会正常的调用close方法

2,前端断网:没有任何回调

3,查资料说长时间不连也会出现断开的情况,未做测试

为了简化开发时间,直接采用了一个websocket库:reconnecting-websocket.js

测试了前两种场景都能正常的重连成功

使用方法很简单:

1,引入reconnecting-websocket.js库,下载地址:github.com/joewalnes/r…

我采用的是把代码直接复制到我的js里面

2,在vue项目里面引入对应的方法

import ReconnectingWebSocket from '../../assets/js/reconnectWebsocket'

3,替换websocket类,只需要改一个地方

    initWebSocket () { // 初始化weosocket
      const wsuri = 'ws://localhost:8080/websocket/' + this.userInfo.operatorId
      this.websock = new ReconnectingWebSocket(wsuri)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen () { // 连接建立之后执行send方法发送数据
      console.log('websokcet 连接成功')
    },
    websocketonerror (e) { // 连接建立失败重连
      console.log('websokcet 连接出错:' + e)
    },
    websocketonmessage (e) { // 数据接收
      if (this.messageList.length < 10) {
        this.messageList.unshift(e.data)
      } else {
        this.messageList.pop()
        this.messageList.unshift(e.data)
      }
    },
    websocketsend (Data) { // 数据发送
      this.websock.send(Data)
    },
    websocketclose (e) { // 关闭
      console.log('websocket断开连接')
    }

注意:这个时候在error里面不用重连了,其他的和原生的websocket写法一样

后面会写一篇文章详细的介绍reconnecting-websocket.js实现的原理,请参考我的其他文章