Vue establish long WebSocket connection

scenes to be used:

  After the data in project development, back-end need to deal with a series of logic, or wait for a third party in return for processing returned to the front end, it may be a long time, back-end and front-end does not know when to deal with (a long time words will reach about 10 minutes), if the ordinary HTTP connection, the front and rear end can not always keep in touch trouble when polling mechanism may also be required, so use WebSocket connection the effect is quite good.

usage time:

  After completion of loading interface, built on WebSocket connection, the front end of this time may also send a request for normal HTTP, after the rear end until processed by the established WebSocket returned to the front end of the connection, the front end of the corresponding operation according to the data for return.

Code shows:

<template>
</template>
<script>
export default {
  data() {
    return{
      // User Id
      userId:'',
      appid:'',
      // event type
      type:'',
      msg:'',
      wsUrl:''
    }    
  },
  methods: {
    // Initialize weosocket
    initWebSocket () {
      if (typeof WebSocket === "undefined") {
        alert ( "Your browser does not support WebSocket");
        return false;
      }
      const wsuri = 'ws: // (WebSocket rear end address) / websocket /' + this.userId + '/' + this.appid // websocket address

      this.websock = new WebSocket(wsuri);
      this.websock.onopen = this.websocketonopen;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    //connection succeeded
    websocketonopen() {
      console.log ( "WebSocket connection is successful");
      // Add the heartbeat detection, send data once every 30 seconds to prevent disconnection (which is related with the setting of the server, if the server is not set how often the message is not disconnected, the heartbeat may not be provided)
      let self = this;
      this.timer = setInterval(() => {
        try {
          self.websock.send('test')
          the console.log ( 'Send Message');
        }catch(err){
          console.log ( 'disconnected:' + err);
          self.connection()
        }
      }, 30000)
    },
    // return the rear end of the received data, may be processed as required
    websocketonmessage(e) {
      var vm = this;
      let data1Json = JSON.parse(e.data);
      console.log(data1Json);
    },
    // connection establishment fails to reconnect
    websocketonerror(e) {
      console.log ( `connection information failure:`, e);
      this.initWebSocket (); // connection failed attempt to reconnect
    },
    // close the connection
    websocketclose(e) {
      console.log ( "disconnected", e);
    }
  },
  created() {
    if (this.websock) {
      this.websock.close (); // close connection websocket
    }
    this.initWebSocket();
  },
  destroyed() {
    Ws destroyed // close connection page
    if (this.websock) {
      this.websock.close(); // 关闭websocket
    }
  }
};
</script>

Review Questions:

  Problems encountered in actual use: Sometimes pages link has not been established on, but the back-end data has been handled well, this time pushing to the front, the front end does not receive.

solution:

  1) The simplest way: Let the back-end delay of a few seconds again and again

  Advantage: Simple

  Disadvantages: reduced performance

  2) method after optimization: use Redis to save the user's login status, the user's data cache, wait until after the connection is established again and again, putting out on the empty Redis

Guess you like

Origin www.cnblogs.com/helen9822/p/11793328.html