ng2 stomp client - 重新连接后如何重新订阅?

时间:2017-09-19 16:11:36

标签: angular stomp

我使用ng2-stomp-service订阅套接字:

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

有时连接丢失了,我看到了#34;哎呀!连接丢失。重新连接..."

此时,Stomp会自动重新连接,但它永远不会重新订阅,因此我可以再次开始接收数据。

在Stomp自动重新建立连接后如何重新订阅,以便我可以再次开始接收数据?

2 个答案:

答案 0 :(得分:1)

Stomp Service尝试在调用onError方法时重新连接。

我解决了覆盖控制器中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()

答案 1 :(得分:0)

我仍然愿意接受这方面的建议,但就目前而言,我想分享一下我目前解决这个问题的方式。

在stomp对象上,我注意到有几个属性,包括另一个名为stomp的对象。在那里,我找到了一个名为subscriptions的对象,它为每个当前订阅都有一个属性(以字符串' sub - '后跟一个数字命名,表示订阅的索引...所以第一个订阅是sub-0'。如果重新连接,所有这些属性都会被删除,从而产生一个空对象。

所以在我的代码中,我所做的就是(每秒一次)通过检查订阅属性是否具有任何属性来检查我是否需要重新订阅。

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
   }
}

是的,这很难看......但这就是为什么我仍然愿意接受建议。

相关问题