Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a SignalR ConnectionId, can I tell whether that session is still connected?

Tags:

signalr

For a variety of reasons, when a SignalR connection is established, I'm storing that ConnectionId in my datastore. However, those connection records can get orphaned, for instance, if SignalR restarts. (I've also observed behavior that makes me wonder if OnDisconnected() is getting called correctly, though I'm less sure of this.)

But for whatever reason, I periodically end up with records in my database that are orphaned, and I'd like to be able to prune those, and remove any ConnectionID listed that isn't actually connected anymore - presumably by having SignalR tell me whether this ConnectionID is still associated with a live session.

I've looked through the SignalR source, and it's not leaping out at me how best to accomplish this. Is there a reasonable way to do it?

like image 978
Ken Smith Avatar asked Jan 03 '13 01:01

Ken Smith


People also ask

Does SignalR keep connection alive?

You can handle this event if you want your application to take some action when a transport connection is lost. The default keepalive timeout period is currently 20 seconds. If your client code tries to call a Hub method while SignalR is in reconnecting mode, SignalR will try to send the command.

How do I set SignalR connection timeout?

Timeout configuration for SignalR can be set in Application_Start method of Global class in Global. asax. cs file. // Wait a maximum of 30 minutes after a transport connection is lost // before raising the Disconnected event to terminate the SignalR connection.


1 Answers

The way to accomplish this is to track clients on your own. From your post it seems like you are already doing this (still provided code in case you aren't) but this is the only way to know if a client is connected. The SignalR server triggers the onconnected/ondisconnected events in as a way of indicating if a client is or is not connected.

I'd recommend ensuring that your not re-instantiating records in your database on reconnect incorrectly.

For instance (super simple example):

class myHub
{
    private static List<String> _connectedClients = new List<String>();

    public override Task OnConnected()
    {
        _connectedClients.Add(Context.ConnectionId);
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        _connectedClients.Remove(Context.ConnectionId);
        return base.OnDisconnected();
    }

    public static bool IsConnected(string cid)
    {
        return _connectedClients.Contains(cid);
    }
}

You can now call IsConnected on the hub to determine if a connection ID is currently connected.

like image 97
N. Taylor Mullen Avatar answered Apr 03 '23 13:04

N. Taylor Mullen