2017-10-20 373 views
0

我需要將客戶端應用程序(SignalR)重新連接到服務器應用程序(SignalR),直到它連接。用HubConnection在SignalR中重新連接的正確邏輯

但它總是有ConnectionState.Reconnecting ...所以我不知道如何重新連接。

我發現這種方法Best practice for reconnecting SignalR 2.0 .NET client to server hub 說,我們必須重新HubConnection作爲一個獨特的工作方法......

任何線索?

我的代碼是

System.Timers.Timer connectionChecker = new System.Timers.Timer(20000); 
HubConnection Connection { get; set; } 

    private void ConnectionChecker_ElapsedAsync(object sender, System.Timers.ElapsedEventArgs e) 
      { 
       if (Connection.State == ConnectionState.Disconnected) 
       { 
        connectionChecker.Stop(); 
        ForceConnectAsync().Start(); // In this method await Connection.Start(); 
       } 
       else if (Connection.State == ConnectionState.Connecting) 
       { 
        // After conection lost it keeps this state ALWAYS. 
        // But once server is up it still has this state. 
       } 
       else if (Connection.State == ConnectionState.Reconnecting) 
       { 
       } 
       else if (Connection.State == ConnectionState.Connected) 
       { 
       } 
      } 
+0

[重新連接SignalR 2.0 .NET客戶機到服務器集線器最佳實踐]的可能的複製(HTTPS:/ /stackoverflow.com/questions/23375043/best-practice-for-reconnecting-signalr-2-0-net-client-to-server-hub) –

回答

0

所以我發現這個最冷溶液Best practice for reconnecting SignalR 2.0 .NET client to server hub

private async Task<bool> ConnectToSignalRServer() 
{ 
    bool connected = false; 
    try 
    { 
     Connection = new HubConnection("server url"); 
     Hub = Connection.CreateHubProxy("MyHub"); 
     await Connection.Start(); 

     //See @Oran Dennison's comment on @KingOfHypocrites's answer 
     if (Connection.State == ConnectionState.Connected) 
     { 
      connected = true; 
      Connection.Closed += Connection_Closed; 
     } 
     return connected; 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine("Error"); 
     return false; 
    } 
} 

private async void Connection_Closed() 
{ 
    if(!IsFormClosed) // A global variable being set in "Form_closing" event of Form, check if form not closed explicitly to prevent a possible deadlock. 
    { 
     // specify a retry duration 
     TimeSpan retryDuration = TimeSpan.FromSeconds(30); 

     while (DateTime.UtcNow < DateTime.UtcNow.Add(retryDuration)) 
     { 
      bool connected = await ConnectToSignalRServer(UserId); 
      if (connected) 
       return; 
     } 
     Console.WriteLine("Connection closed") 
    } 
}