参考:https://blog.csdn.net/hzzhoushaoyu/article/details/49407835

 

import SockJS from "sockjs-client";

// websocket 配置
  stompClient: any = null;  

// 连接websocket
  connection() {
    const that = this;
    // 建立连接对象
    let socket = new SockJS(`http://xxxx`, null, { timeout: 50000 });
    // 获取STOMP子协议的客户端对象
    that.stompClient = Stomp.over(socket);
    that.stompClient.debug = (str: any) => {
      // console.log(str + "\n");
    };
    // 向服务器发起websocket连接
    that.stompClient.connect(
      that.headers,
      // 订阅服务
      () => {
        that.stompClient.subscribe("/xxxx", (msg: any) => {
          // 订阅实时趋势数据
          if (msg.body) {
            const res = JSON.parse(msg.body);
            const items = res.data.datas.length > 0 ? res.data.datas : null;
            if (items) {
              // that.chart.appendData({
              //   seriesIndex: 0,
              //   data: items
              // })
              that.sourceData = that.sourceData.concat(items)
              that.updateChart()
              that.updateTime = moment(items[items.length - 1][0]).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        });
        that.stompClient.subscribe("/user/queue/error", (msg: any) => {
          // 订阅错误消息
          console.log("错误消息", msg);
          that.$notification.error({
            message: '错误消息',
            description: msg
          });
        });
      },
      // 错误处理
      (err: any) => {
        // 连接发生错误时的处理函数
        console.log("连接失败", err);
        // that.$notification.error({
        //   duration: 99,
        //   message: '连接失败',
        //   description: err
        // });
        // 连接失败后1秒后重新请求数据并连接
        setTimeout(() => {
          that.stompClient = null;
          that.resetHeader()
          that.connection()
          that.getSourceData()
        }, 1000)
      }
    );
  }

  // 断开连接
  disconnect() {
    this.resetHeader()
    if (this.stompClient) {
      this.stompClient.disconnect();
      this.stompClient = null;
    }
  }

使用SockJS连接还没建立起来,往通道发送数据,会报错

The connection has not been established yet

如果使用WebSocket会报这个错

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

 

Logo

前往低代码交流专区

更多推荐