Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR: Detecting Alive Connection in C# clients

Tags:

c#

signalr

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)?

like image 993
Kiong Avatar asked Jul 22 '14 03:07

Kiong


1 Answers

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.

like image 96
halter73 Avatar answered Nov 08 '22 06:11

halter73