如何在SirnalR中处理重新连接并在此之后重新订阅

时间:2019-07-05 17:55:19

标签: react-native signalr

我正在开发带有react-native和SignalR套接字的移动应用程序。当套接字关闭时,我需要处理重新连接的帮助。首次启动该应用程序时,SignalR集线器连接成功启动,并通过来自套接字的来自服务器的数据渲染主屏幕,其中每1-2秒更改一次数据。问题是当我锁定设备30秒钟时。或更多,SignalR套接字正在关闭>我尝试在调用onclose()时打开一个新连接,但我丢失了所有订阅。另一个问题有时是当我尝试从onclose()重新连接时,收到以下错误消息:“无法启动处于断开状态的连接”。我的问题是:如何在连接关闭时正确地重新连接?并再次应用所有订阅,因为它们在断开连接后会丢失?

This is my SignalR connection

class SignalR extends Component {
    constructor() {

       this.connection = new signalR.HubConnectionBuilder()
           .configureLogging(signalR.LogLevel.Debug)
           .withUrl(this.core.constants.BASE_WS_URL)
           .build();

     this.connection.onclose(() => {
      console.info(this.connection)
      console.info('connection has been closed!')
      await this.open(); // trying to reconnect
     });

    }

    openConnection = async () => {
       try {
            console.log('WebSocket connecting');
            await connection.start();
            await this.setState({ isConnected: true });
            console.log('WebSocket connected');
      } catch(e) {
          console.log('WebSocket failed to connect:\n' + e.message);

          setTimeout(async () => await this.openConnection(), 5000);
       }
   };

   subscribe(params) {
     // this method is calld in componentDidMount()
   }
}

这是主屏幕

import SignalR from '../../../';

class Home extends Component {

    componentDidMount(){
      this.subscription = SignalR.subscribe(parameters);
    }
}

0 个答案:

没有答案