How To Get List Of Connected Clients In SignalR

In this blog, I am going to explain how to know how many clients are currently connected with SignalR Server.

I have not found any direct way to call. So, we need to write our own logic inside a method provided by SignalR Library.
 
There is a Hub class provided by the SignalR library.
 
In this class, we have 2 methods.
  1. OnConnectedAsync()
  2. OnDisconnectedAsync(Exception exception)
So, the OnConnectedAsync() method will add user and OnDisconnectedAsyn will disconnect a user because when any client gets connected, this OnConnectedAsync method gets called.

In the same way, when any client gets disconnected, then the OnDisconnectedAsync method is called.
 
So, let us see it by example.
 
Step 1
 
Here, I am going to define a class SignalRHub and inherit the Hub class that provides virtual method and add the Context.ConnectionId: It is a unique id generated by the SignalR HubCallerContext class.
  1. public class SignalRHub : Hub  
  2. {  
  3. public override Task OnConnected()  
  4. {  
  5. ConnectedUser.Ids.Add(Context.ConnectionId);  
  6. return base.OnConnected();  
  7. }  
  8. public override Task OnDisconnected()  
  9. {  
  10. ConnectedUser.Ids.Remove(Context.ConnectionId);  
  11. return base.OnDisconnected();  
  12. }  
  13. }  
Step 2
 
In this step, we need to define our class ConnectedUser with property Id that is used to Add/Remove when any client gets connected or disconnected.
 
Let us see this with an example.
  1. public static class ConnectedUser  
  2. {  
  3. public static List<string> Ids = new List<string>();  
  4. }  
Now, you will get the result of currently connected client using ConnectedUser.Ids.Count.
 
Note
 
As you see, here I am using a static class that will work fine when you have only one server, but when you will work on multiple servers, then it will not work as expected. In this case, you could use a cache server like Redis cache, SQL cache.