从客户端检测SignalR连接丢失

3

我正在将一个简单的应用程序连接到托管我的Web应用程序的服务器上。我的Web应用程序使用SignalR 2。一切都很顺利,我的小应用程序可以与Web应用程序同步,并接收从中发送的消息。但是,当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个回答

3
您可以尝试这样做:
这来自于SignalR官方示例。
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事件:

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);
}

我尝试了这个例子,它运行良好: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。 - Quentin Roger
@NacerFarajzadeh 你是如何尝试重新启动连接的? - Quentin Roger
实际上,我不想重新启动连接。我该怎么做呢?有没有安全的方法可以实现这个? - LeXela-ED
@NacerFarajzadeh 我编辑了我的答案,提供了一种重新连接到SignalR的方法。 - Quentin Roger
非常感谢 @Quentin Roger。问题已解决。 :-) - LeXela-ED
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接