在客户端检测SignalR中的连接丢失

在客户端检测SignalR中的连接丢失

问题描述:

我将一个简单的应用程序连接到托管我的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 
} 

你可以尝试这样的事情:

从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您是如何尝试重新启动连接的? –