2016-05-30 79 views
0

我將一個簡單的應用程序連接到託管我的Web應用程序的服務器。我的Web應用程序使用SignalR 2.一切都很順利,我的小應用程序可以與Web應用程序同步並接收從它發送的消息。但是,當網頁更新或服務器重新啓動並失去連接時,應用程序無法理解連接從服務器丟失。以下是我的代碼:在客戶端檢測SignalR中的連接丟失

// initializing connection 
HubConnection connection; 
IHubProxy hub; 

connection = new HubConnection(serverAddress); 
hub = connection.CreateHubProxy("MyPanel"); 
hub.On<string>("ReciveText", (msg) => recieveFromServer(msg)); 

線程檢查連接每隔1分鐘,但每次檢查時,連接的狀態是「已連接」,而從服務器端的連接丟失。有什麼我在這裏失蹤?

if (connection.State == ConnectionState.Disconnected) 
{ 
    // try to reconnect to server or do something 
} 

回答

2

你可以嘗試這樣的事情:

從signalR官方自帶的例子。

connection = new HubConnection(serverAddress);  
connection.Closed += Connection_Closed; 

/// <summary> 
/// If the server is stopped, the connection will time out after 30 seconds (default), and the 
/// Closed event will fire. 
/// </summary> 
void Connection_Closed() 
{ 
//do something 
} 

您可以使用StateChanged事件太像這樣:

connection.StateChanged += Connection_StateChanged; 

private void Connection_StateChanged(StateChange obj) 
{ 
     MessageBox.Show(obj.NewState.ToString()); 
} 

編輯

你可以嘗試每15秒重新與類似的東西:

private void Connection_StateChanged(StateChange obj) 
    { 

     if (obj.NewState == ConnectionState.Disconnected) 
     { 
      var current = DateTime.Now.TimeOfDay; 
      SetTimer(current.Add(TimeSpan.FromSeconds(30)), TimeSpan.FromSeconds(10), StartCon); 
     } 
     else 
     { 
      if (_timer != null) 
       _timer.Dispose(); 
     } 
    } 

    private async Task StartCon() 
    { 
     await Connection.Start(); 
    } 

    private Timer _timer; 
    private void SetTimer(TimeSpan starTime, TimeSpan every, Func<Task> action) 
    { 
     var current = DateTime.Now; 
     var timeToGo = starTime - current.TimeOfDay; 
     if (timeToGo < TimeSpan.Zero) 
     { 
      return; 
     } 
     _timer = new Timer(x => 
     { 
      action.Invoke(); 
     }, null, timeToGo, every); 
} 
+0

謝謝。我使用了你的解決方案,但沒有奏效。當服務器關閉時,連接狀態將變爲「斷開連接」。然後它嘗試重新連接。一段時間後,它會連接,但服務器無法檢測到連接! :( –

+0

我試過這個例子,它工作正常https://code.msdn.microsoft.com/windowsdesktop/Using-SignalR-in-WinForms-f1ec847b,你可以在這裏獲得更多關於理解和處理SignalR中連接生命期事件的信息: http://www.asp.net/signalr/overview/guide-to-the-api/handling-connection-lifetime-events –

+0

@NacerFarajzadeh您是如何嘗試重新啓動連接的? –