SignalR, how to validate if a connection id is still active?

1.9k views Asked by At

As the title says, how to validate if a connection id is still active using SignalR? I have something similar as below where I map the connection ids to a user id. The problem is that in rare cases OnDisconnectedAsync does not triggeres.

Then I can't make the feature where the user is joining or leaving because it thinks that the user still have a connection.

I do have a "pinger" which run each 5 minutes that is updating a expire date but it is not reliable. What I want is something like loop through all connection ids and verify if they are still active.

How can this be done? I thought maybe I can send a message to all connection ids for user X and see if I get something back and then do some kind of cleanup?

public class Chat : Hub
{
    private IConnectionManager _manager;
    public Chat(IConnectionManager manager)
    {
        _manager = manager;
    }
public override Task OnConnectedAsync()
    {
       // Add connectionId and any other info you want to your connectionManager
        _manager.Add(Context.ConnectionId, Context.User, Context.GetHttpContext());
    }
public override Task OnDisconnectedAsync(Exception exception)
    {
       _manager.Remove(Context.ConnectionId);
    }
}
1

There are 1 answers

1
Kiril1512 On

SignalR has its own "pinger".

//
// Summary:
//     Gets or sets the interval used by the server to send keep alive pings to connected
//     clients. The default interval is 15 seconds.
public TimeSpan? KeepAliveInterval { get; set; } 

And you can configure it on Startup like:

services.AddSignalR(hubOptions =>
{
    hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(hostConfiguration.SignalR.KeepAliveInterval);
}

So basically if the client will not respond in the defined timespan, it will trigger OnDisconnectedAsync.