SignalR: Detecting Alive Connection in C# clients

2019-02-08 17:07发布

I am currently developing an application using SignalR (2.1) Hubs.

I have 1 WPF client and the other is a WCF client. Everything works fine in that they are passing the messages perfectly.

The only problem I faced now is that I noticed the OnDisconnected is not fired at all when the application shuts down for reasons such as auto-restarts, WCF server went down and a few others. The timeout is the default of 30 seconds. It is never called even after 1 day has passed (I tried). However, the timeout works for Web Clients.

It only works when I call hub.connection.stop().

The Ondisconnected method however works very well when the client is a browser.

Thus, I would like to ask whether there is any way for Signal R Hub side to be able to check whether the client is still connected or has already dropped out (such as a ping)?

标签: c# signalr
2条回答
Bombasti
2楼-- · 2019-02-08 17:22

In SignalR 2.1.0, there is a new overload to OnDisconnected that takes a bool indicating whether the client disconnected gracefully or not. The reasoning behind this change is explained in the "Breaking Changes" section of the 2.1.0 release notes.

Your new OnDisconnected method could look something like this:

public override Task OnDisconnected(bool stopCalled)
{
    if (stopCalled)
    {
        // We know that Stop() was called on the client,
        // and the connection shut down gracefully.
    }
    else
    {
        // This server hasn't heard from the client in the last ~35 seconds.
        // If SignalR is behind a load balancer with scaleout configured, 
        // the client may still be connected to another SignalR server.
    }

    return base.OnDisconnected(stopCalled);
}

The old OnDisconnected method that doesn't take a bool is not called for non-graceful disconnects, so if you are using that event, that could explain the issue you are seeing.

Prior to 2.1.0, the (only) OnDisconnected method which didn't take a parameter was called for both graceful and non-graceful disconnects. Since this change in behavior has caused several reported issues, the old OnDisconnected overload is being removed in SignalR's upcoming 2.1.1 release.

This will cause applications that use SignalR's old OnDisconnected method to fail to compile when built against SignalR 2.1.1. While this isn't ideal, it will hopefully make developers aware of this breaking change so they have the opportunity to modify their apps appropriately before deploying them.

查看更多
戒情不戒烟
3楼-- · 2019-02-08 17:23

I found that my Client would not reconnect if I forced the Server to shut down the connection. (I'd get a WSSockets error)

So, for me, the fix was:

con = new HubConnection(_url);
con.Error += (exception) => Error(exception);
con.Start();

then, in the Error method, attempt to reconnect by calling the above code again.

查看更多
登录 后发表回答