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 a variable

    Data () {return {// webSocket object webSocket: null, // webSocketUrl address webSocketUrl: null, // Connection identifier avoid duplicate connection isConnect: Rec: null, // Heartbeat send/return message checkMsg: {HHH: TimeoutObj: null,}} timeoutObj: null,}}Copy the code
  2. 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; Onopen = thate. websocket. onopen; // When webSocket receives a message from the server, the onMessage method is called that.websocket.onMessage = that.websocketonMessage; // When webSocket is closed for any reason (normal or abnormal), onclose is called that.websocket. onclose = that. // When webSocket is down due to an exception (server deployment, disconnection, etc.), Websocket. onError = th.websocketonError; // reConnect = th.websocketonError; }Copy the code
  4. Websocketonopen function

    websocketonopen() { let that = this; console.log('open'); That. IsConnect = true; TimeoutObj = setTimeout(function() {if (thate.isconnect); // If (thate.isconnect); // If (thate.isconnect) that.webSocket.send(that.checkMsg); }, that.timeout); }Copy the code
  5. Websocketonerror function

    websocketonerror() { let that = this; console.log('error'); IsConnect = false; // reConnect(); }Copy the code
  6. Websocketonmessage function

    Websocketonmessage (e) {let that = this; console.log(e.data); // Reset the heartbeat clearTimeout(thate.timeoutobj) after getting the message; 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'); IsConnect = false; // reConnect(); }Copy the code
  8. Define the reconnection function

    reConnect() { let that = this; Console. log(' Try to reconnect '); If (that. IsConnect) {return; } clearTimeout(that.rec); Rec = setTimeout(function() {that.createwebSocket (); }, 5000); }Copy the code