繁体   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