最近的工作主要轉到前端了,之前是只是改寫bug,做一些樣式調整的工作,現在接了一個完整的需求。這個需求中要用到socket技術,看了一下之前同事用的是stomopjs庫,正好查查資料是怎么用的,參考一下。仔細看下來和iOS中使用方法類似,畢竟都是同一個websocket協議。
-
安裝
sockjs-client
和stompjs
npm install sockjs-client
npm install stompjs
-
引入socket庫
import SockJS from 'sockjs-client';
import Stomp from 'stompjs'
-
使用
- 初始化變量
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,有時間查查怎么用的