vue使用sockjs報錯The connection has not been established yet

參考: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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章