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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With