2016-05-30 7 views
0

私のWebアプリケーションをホストするサーバーに簡単なアプリケーションを接続しています。私のWebアプリケーションはSignalR2を使用しています。すべてがスムーズに進み、小さなアプリケーションはWebアプリケーションと同期し、そこから送信されたメッセージを受信できます。しかし、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イベントを使用することができます:あなたはそのようなもので、すべて15秒を再接続しようとすることができます

connection.StateChanged += Connection_StateChanged; 

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

EDIT

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のConnection Lifetime Eventsを理解して処理する方法について詳しく知ることができます: http://www.asp.net/signalr/overview/guide-to-the-api/handling-connection-lifetime-events –

+0

@NacerFarajzadeh接続を再開しようとしましたか? –

関連する問題