Vue+WebSocket 實現頁面實時重新整理長連線

byteblogs發表於2019-05-27

vue實現與websocket實現長連結

    export default {
        data() {
            return {
                websock: null,
            }
        },
        created(){
           //頁面剛進入時開啟長連線
            this.initWebSocket()
       },
       destroyed: function() {
        //頁面銷燬時關閉長連線
      this.websocketclose();
    },

    methods: { 
      initWebSocket(){ //初始化weosocket 

        const wsuri = 127.0.0.1:8080 + "/websocket/threadsocket";//ws地址
        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連線成功");
      },
      websocketonerror(e) { //錯誤
        console.log("WebSocket連線發生錯誤");
      },
      websocketonmessage(e){ //資料接收 
        const redata = JSON.parse(e.data);
           // 接收資料
        console.log(redata.value); 
      }, 

      websocketsend(agentData){//資料傳送 
        this.websock.send(agentData); 
      }, 

      websocketclose(e){ //關閉 
        console.log("connection closed (" + e.code + ")"); 
     },
   }, 
  }

轉載 https://www.51csdn.cn/article/377.html

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章