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

时间:2016-05-30 07:11:59

标签: connection client signalr

我正在将一个简单的应用程序连接到托管我的web-pplication的服务器。我的Web应用程序使用SignalR 2.一切顺利,我的小应用程序可以与Web应用程序同步并接收从它发送的消息。但是,当更新网页或服务器重新启动并且它失去连接时,应用程序无法理解连接是否从服务器丢失。以下是我的代码:

// 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
}

1 个答案:

答案 0 :(得分:2)

你可以尝试这样的事情:

来自signalR的官方例子。

MaxResults

你也可以使用connection = new HubConnection(serverAddress); connection.Closed += Connection_Closed; /// <summary> /// If the server is stopped, the connection will time out after 30 seconds /// the 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());
}