【问题标题】:ng2 stomp client - how to re-subscribe after re-connecting?ng2 stomp 客户端 - 重新连接后如何重新订阅?
【发布时间】:2017-09-19 16:11:35
【问题描述】:

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

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

有时连接丢失,我看到“糟糕!连接丢失。重新连接...”

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

Stomp自动重新建立连接后如何重新订阅,才能重新开始接收数据?

【问题讨论】:

    标签: angular stomp


    【解决方案1】:

    当调用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()

    【讨论】:

      【解决方案2】:

      我仍然对这里的建议持开放态度,但现在,我想分享一下我目前解决此问题的方法。

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

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

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

      是的,它很丑……但这就是为什么我仍然愿意接受建议。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-15
        • 1970-01-01
        • 1970-01-01
        • 2020-11-16
        • 2022-11-07
        • 2021-09-27
        • 2021-08-25
        相关资源
        最近更新 更多