When the back-end server is down or restarted, the front-end Vue continuously reconnects to webSocket.

Problem recurrence: When the background service is restarted, the webScoket of the front-end connection is broken, and the user experience is not good until the page is refreshed. In some service scenarios, such as the large screen of the hardware monitoring system, the page is not allowed to be refreshed. Therefore, the front-end needs to discover that the webSocket is broken and initiate the connection continuously.

Call reconnection function when webSocket life cycle onclose and onError, increase heartbeat detection.

Solution: 1. Create variables

data() {    

    return {        

/ / the webSocket object

        webSocket: null,        

/ / webSocketUrl address

        webSocketUrl: null,        

// Avoid repeated connections

        isConnect: false.

// Rec is the code used to store delayed requests to re-create WebSocket connections after disconnection

        rec: null,        

// Message sent/returned by heartbeat

        checkMsg: {hhh: 'heartbeat'},        

// Send heartbeat packets at intervals. Set this parameter to 20s

        timeout: 20000,        

// Delay sending message object (start heartbeat to create this object, after receiving the message to reset the object)

        timeoutObj: null,    

   }

}

Copy the code

2. Create a webSocket connection

// Create a webSocket connection

createWebSocket() {    

    let that = this;    

    that.webSocket = new WebSocket(that.webSocketUrl);

    that.initWebsocket();

}

Copy the code

3. Initialize the webSocket connection

initWebsocket() {    

    let that = this;    

// The onopen method is called after the WebSocket connection is established

    that.webSocket.onopen = that.websocketonopen;    

// The onMessage method is called when websocket receives a message from the server

    that.webSocket.onmessage = that.websocketonmessage;

// When webSocket is closed for any reason (normal or abnormal), onclose is called

    that.webSocket.onclose = that.websocketclose;    

// The onError method is called when webSocket is down due to an exception (server deployment, network outage, etc.)

// Call reConnect to the server in onError

    that.webSocket.onerror = that.websocketonerror;

}

Copy the code

4. Websocketonopen function

websocketonopen() {    

    let that = this;    

    console.log('open');    

// Modify the identity after the connection is established

    that.isConnect = true;    

// The heartbeat starts after the connection is established

// Because nginx is usually set to disconnect if there is no data transfer in 60s, it is timed to send data

    that.timeoutObj = setTimeout(function() {        

        if (that.isConnect)    

            that.webSocket.send(that.checkMsg);    

            }, that.timeout);

 }

Copy the code

5. Websocketonerror function

websocketonerror() {    

   let that = this;    

   console.log('error');    

// Modify the identifier after the connection is disconnected

   that.isConnect = false;    

// Connection error requires reconnection

   that.reConnect();

}

Copy the code

6. Websocketonmessage function

websocketonmessage(e) {    

// Get the data and handle your business

    let that = this;    

    console.log(e.data);                    

// Resets the heartbeat after getting the message

    clearTimeout(that.timeoutObj);    

    that.timeoutObj = setTimeout(function() {    

        if (that.isConnect)

        that.webSocket.send(that.checkMsg);    },

        that.timeout);

}

Copy the code

7. Websocketclose function

websocketclose() {    

    let that = this;    

    console.log('close');    

// Modify the identifier after the connection is disconnected

    that.isConnect = false;    

// Connection error requires reconnection

    that.reConnect();

}

Copy the code

8. Define the reconnection function

reConnect() {    

    let that = this;    

    console.log('Try to reconnect');    

// If it is already connected, it is not reconnected

    if (that.isConnect) {        

        return;    

    }    

    clearTimeout(that.rec);    

// Delay reconnection for 5 seconds to avoid frequent requests for reconnection

    that.rec = setTimeout(function() {    

        that.createWebSocket();    }, 5000);

}

Copy the code

If you also want to learn the front-end development technology, now in the process of learning the front have met any about learning method, learning course, learning efficiency and so on problems, you can apply for to join my qq group: before 114, in 6649 after 671, there were many front-end study materials Giant bo free access to the interview, hope to be able to help you.