Scenario: The project uses websocket to make a simple long connection to display the login user information in real time

The code is as follows:

Tests for some exception scenarios:

1, server restart: the close method will be called normally

2. Front-end disconnection: No callback

3, the data said that a long time not connected will also be disconnected, did not test

To simplify development time, a websocket library was used directly: reconnection-websocket.js

Test the first two scenarios can be normal reconnection success

How to use it is simple:

Reconnecting -websocket.js library: github.com/joewalnes/r…

What I do is copy the code directly into my JS

2. Introduce corresponding methods into THE VUE project

import ReconnectingWebSocket from '.. /.. /assets/js/reconnectWebsocket'Copy the code

3. Replace the WebSocket class with only one change

InitWebSocket () {/ / initialization weosocket const wsuri = 'ws: / / localhost: 8080 / websocket/' + enclosing the 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 data console.log('websokcet connection succeeded ')}, Websocketonerror (e) {// Connection failed to establish console.log('websokcet connection error :' + e)}, If (this.messagelist.length < 10) {this.messagelist.unshift (e.ata)} else {this.messagelist.unshift (e.ata)} else { This.messagelist.pop () this.messagelist.unshift (e.ata)}}, webSocketSend (Data) {// Data is sent this.websock. Send (Data)}, Websocketclose (e) {// Close console.log('websocket disconnects ')}Copy the code

Note: there is no need to reconnect in error, the rest is written the same as in native Websocket

I’ll write an article on how to implement reconnecting-websocket.js in more detail, please refer to my other articles