vue中使用websocket


1. 在utils下面新建websocket.js

class WebsocketConn {
  constructor(url, cb) {
    this.cb = cb;
    this.url = url
    this.ws = null;
    this.lockReconnect = false;  //避免ws重復連接
    this.timeout = 30000; // 心跳檢測時間
    this.heartCheckTimer = null // 心跳檢測定時器
    this.heartCheckServerTimer = null;
  }

  heartCheckToReset() {
    clearTimeout(this.heartCheckTimer);
    clearTimeout(this.heartCheckServerTimer);
    return this;
  }

  heartCheckToStart() {
    this.heartCheckTimer = setTimeout(() => {
      //這里發送一個心跳,后端收到后,返回一個心跳消息,
      //onmessage 拿到返回的心跳就說明連接正常
      this.ws.send("ping");
      console.log("ping!")
      this.heartCheckServerTimer = setTimeout(() => {//如果超過一定時間還沒重置,說明后端主動斷開了
        this.ws.close();     //如果onclose會執行reconnect,我們執行ws.close()就行了.如果直接執行reconnect 會觸發onclose導致重連兩次
      }, this.timeout)
    }, this.timeout)
  }

  create() {
    try{
      if('WebSocket' in window){
        this.ws = new WebSocket(this.url);
      }
      this.initEventHandle();
    }catch(e){
      this.reconnect(this.url);
      console.log(e);
    }
  }

  initEventHandle() {
    this.ws.onclose = () => {
      this.reconnect(this.url);
      console.log("websocket 連接關閉!"+ new Date().toLocaleString());
    };
    this.ws.onerror = () => {
      this.reconnect(this.url);
      console.log("websocket 連接錯誤!");
    };
    this.ws.onopen = () => {
      this.heartCheckToReset().heartCheckToStart();      //心跳檢測重置
      console.log("websocket 連接成功!"+new Date().toLocaleString());
    };
    this.ws.onmessage = (event) => {    //如果獲取到消息,心跳檢測重置
      this.heartCheckToReset().heartCheckToStart();      //拿到任何消息都說明當前連接是正常的
      this.cb();
      console.log("websocket 收到消息啦:" + event.data);
    };
  }

  reconnect() {
    console.log("重新連接")
    if(this.lockReconnect) return;
    this.lockReconnect = true;
    setTimeout(() => {     //重連,設置延遲避免請求過多
      this.create(this.url);
      this.lockReconnect = false;
    }, 2000);
  }

  close() {
    this.ws.close();
  }
}

export default WebsocketConn

2. 在組件中使用

1)引入

import WebsocketConn from "@/utils/websocket";

2)定義data

    data: function () {
      return {
        websocket: null,
      }
    }    

3)創建

      createWebSocket() {
        let _this = this;
        let _wsurl = `${httpConfig.wsHost}api/websocket_service/v1/ws/get/business?business_id=${localStorage.businessId}&session_id=${localStorage.sessionId}`
        let _getMessage = () => {
          var msg = JSON.parse(event.data);
          if ((msg.code == 600 || msg.code == 601) && msg.result.data.length > 0 && !msg.result.data[0].withdrawalUserId) {
            _this.$router.go(0);
          } else {
            console.log(msg.code);
          }
        }
        _this.websocket = new WebsocketConn(_wsurl, _getMessage);
        _this.websocket.create();
      },

4)銷毀

    destroyed() {
      this.websocket.close();
    },

 


免責聲明!

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



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