簡體   English   中英

ng2 stomp客戶端-重新連接后如何重新訂閱?

[英]ng2 stomp client - how to re-subscribe after re-connecting?

我正在使用ng2-stomp-service訂閱套接字:

this.fooSubscription = this.stomp.subscribe('/topic/foo', (res) => {
    console.log('do stuff with res');
});

有時連接丟失,並且我看到“糟糕!連接丟失。正在重新連接...”

到那時,Stomp自動重新連接,但從不重新預訂,因此我可以再次開始接收數據。

在Stomp自動重新建立連接后如何重新訂閱,以便可以再次開始接收數據?

當調用onError方法時,Stomp Service嘗試重新連接。

我解決了覆蓋我的控制器中StompService類的onError方法的問題:

/**
 * Unsuccessfull connection to server
 */
public onError = (error: string ) => {

  console.error(`Error: ${error}`);

  // Check error and try reconnect
  if (error.indexOf('Lost connection') !== -1) {
    if(this.config.debug){
        console.log('Reconnecting...');
    }
    this.timer = setTimeout(() => {
        this.startConnect();
    }, this.config.recTimeout || 5000);
  }
}

具有以下內容:

this.stompService.onError = (error: string) => {

      console.error(`Error: ${error}`);

      // Check error and try reconnect
      if (error.indexOf('Lost connection') !== -1) {
        console.log('Reconnecting...');
        this.timer = setTimeout(() => {

          this.stompService.startConnect().then(() => {

            // ADD HERE THE SUBSCRIPTIONS
            this.socketSubscription = this.stompService.subscribe('/topic/foo', this.response);

          }).catch(err => console.error('Connessione al socket non riuscita'));
        }, this.stompService.config.recTimeout || 5000);
      }
    }

將訂閱添加到startConnect().then()

我仍然願意在這里提出建議,但就目前而言,我想分享我目前解決此問題的方式。

在stomp對象上,我注意到有幾個屬性,包括另一個名為stomp對象。 在這里,我發現了一個名為subscriptions的對象,該對象對每個當前的訂閱都具有一個屬性(以字符串“ sub-”命名,后跟一個數字,代表訂閱的索引...因此,第一個訂閱為“ sub-0 ”重新連接時,所有這些屬性都會被清除,從而導致對象為空。

因此,在我的代碼中,我要做的就是(每秒一次)檢查是否需要重新訂閱,方法是檢查subscriptions屬性是否具有任何屬性。

setInterval(() => {
if (this.stomp.status === 'CONNECTED' && !this.stomp.stomp.subscriptions['sub-0']) {
     this.reestablishSubscriptions();
}, 1000);    

reestablishSubscriptions() {
   this.mySubscription = this.stomp.subscribe('/topic/foo', (res) => {
       // do stuff with subscription responses
   }
   this.myOtherSubscription = this.stomp.subscribe('/topic/foo2', (res) => {
       // do stuff with subscription responses
   }
}

是的,這很丑...但這就是為什么我仍然願意接受建議的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM