Vue+WebSocket 實現頁面實時刷新長連接


<template>
</template>
<script>
export default {
  data() {
    return{
      // 用戶Id
      userId:'',
      appid:'',
      // 事件類型
      type:'',
      msg:'',
      wsUrl:''
    }   
  },
  methods: {
    //初始化weosocket
    initWebSocket() {
      if (typeof WebSocket === "undefined") {
        alert("您的瀏覽器不支持WebSocket");
        return false;
      }
      const wsuri = 'ws://(后端WebSocket地址)/websocket/' + this.userId + '/' + this.appid // websocket地址
 
      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;
    },
    //連接成功
    websocketonopen() {
      console.log("WebSocket連接成功");
      // 添加心跳檢測,每30秒發一次數據,防止連接斷開(這跟服務器的設置有關,如果服務器沒有設置每隔多長時間不發消息斷開,可以不進行心跳設置)
      let self = this;
      this.timer = setInterval(() => {
        try {
          self.websock.send('test')
          console.log('發送消息');
        }catch(err){
          console.log('斷開了:' + err);
          self.connection()
        }
      }, 30000)
    },
    //接收后端返回的數據,可以根據需要進行處理
    websocketonmessage(e) {
      var vm = this;
      let data1Json = JSON.parse(e.data);
      console.log(data1Json);
    },
    //連接建立失敗重連
    websocketonerror(e) {
      console.log(`連接失敗的信息:`, e);
      this.initWebSocket(); // 連接失敗后嘗試重新連接
    },
    //關閉連接
    websocketclose(e) {
      console.log("斷開連接", e);
    }
  },
  created() {
    if (this.websock) {
      this.websock.close(); // 關閉websocket連接
    }
    this.initWebSocket();
  },
  destroyed() {
    //頁面銷毀時關閉ws連接
    if (this.websock) {
      this.websock.close(); // 關閉websocket
    }
  }
};
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM