Get number of listeners, clients connected to SignalR hub Get number of listeners, clients connected to SignalR hub asp.net asp.net

Get number of listeners, clients connected to SignalR hub


There is no way to get this count from SignalR as such. You have to use the OnConnect() and OnDisconnect() methods on the Hub to keep the count yourself.

Simple example with a static class to hold the count:

public static class UserHandler{    public static HashSet<string> ConnectedIds = new HashSet<string>();}public class MyHub : Hub{    public override Task OnConnectedAsync()    {        UserHandler.ConnectedIds.Add(Context.ConnectionId);        return base.OnConnectedAsync();    }    public override Task OnDisconnectedAsync(Exception exception)    {        UserHandler.ConnectedIds.Remove(Context.ConnectionId);        return base.OnDisconnectedAsync(exception);    }}

You then get the count from UserHandler.ConnectedIds.Count.


For version 2.1.1< it should be:

public static class UserHandler{    public static HashSet<string> ConnectedIds = new HashSet<string>();}public class MyHub : Hub{    public override Task OnConnected()    {        UserHandler.ConnectedIds.Add(Context.ConnectionId);        return base.OnConnected();    }    public override Task OnDisconnected(bool stopCalled)    {        UserHandler.ConnectedIds.Remove(Context.ConnectionId);        return base.OnDisconnected(stopCalled);    }}


In SIgnalR(version 2.4.1) it is rather easy:

public int GetOnline(){   return GlobalHost.DependencyResolver.Resolve<ITransportHeartbeat>().GetConnections().Count;}

Just Invoke this method from client (: