Vue + websocket for real-time page refresh and long connection

Time:2021-4-19

Implementation of long link between Vue and websocket

export default {
        data() {
            return {
                websock: null,
            }
        },
        created(){
           //Open long connection when the page first enters
            this.initWebSocket()
       },
       destroyed: function() {
        //Close long connection on page destruction
      this.websocketclose();
    },

    methods: { 
      Initwebsocket() {// initialize weasocket 

        Const wsuri = 127.0.0.1:8080 + "/ websocket / threadsocket"; // WS address
        this.websock = new WebSocket(wsuri); 
        this.websocket.onopen = this.websocketonopen;

        this.websocket.onerror = this.websocketonerror;

        this.websock.onmessage = this.websocketonmessage; 
        this.websock.onclose = this.websocketclose;
       }, 

      websocketonopen() {
        console.log ("websocket connected successfully");
      },
      Websocketonerror (E) {// error
        console.log ("websocket connection error");
      },
      Websocketonmessage (E) {// data reception 
        const redata = JSON.parse(e.data);
           //Receiving data
        console.log(redata.value); 
      }, 

      Websocketsend (AgentData) {// data sending 
        this.websock.send(agentData); 
      }, 

      Websocketclose (E) {// close 
        console.log("connection closed (" + e.code + ")"); 
     },
   }, 
  }

Reprinthttps://www.51csdn.cn/article/377.html


vue

This work adoptsCC agreementReprint must indicate the author and the link of this article