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,有时间查查怎么用的

原文地址:https://www.cnblogs.com/shenyuiOS/p/14940924.html