stompjs使用


最近的工作主要轉到前端了,之前是只是改寫bug,做一些樣式調整的工作,現在接了一個完整的需求。這個需求中要用到socket技術,看了一下之前同事用的是stomopjs庫,正好查查資料是怎么用的,參考一下。仔細看下來和iOS中使用方法類似,畢竟都是同一個websocket協議。

  1. 安裝sockjs-clientstompjs
    npm install sockjs-client
    npm install stompjs

  2. 引入socket庫
    import SockJS from 'sockjs-client';
    import Stomp from 'stompjs'

  3. 使用

    • 初始化變量
      this.bizid = window.location.pathname.substr(6) //直播ID
      this.url = apiPrefix+liveSocket;
      this.headers = { Authorization : store.get('token')};
      this.socket = new SockJS(this.url);
      this.stompClient = Stomp.over(this.socket);
      this.sendUrl = '/formApp/student/accept.'+ this.bizid; //發送地址
      
    • 連接socket服務器,訂閱消息
      // websocket連接
      this.stompClient.connect(this.headers,(frame) => {
      console.log('已連接【' + frame + '】');
        // 訂閱- 發送彈幕
        this.stompClient.subscribe(`/topic/getResponse.${this.bizid}`, response => {
            console.log('收到的消息:', response);
            if(response) {
              result = JSON.parse(response.body);
            }
        })
      }, (err) => {
        // 連接發生錯誤時的處理函數
        console.log(err);
      })
      
    • 發送消息
        this.stompClient.send(this.sendUrl,this.headers,JSON.stringify(data));
      

這個項目中用到了umi, dva,有時間查查怎么用的


免責聲明!

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



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