Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of listeners, clients connected to SignalR hub

Is there a way to find out the number of listeners (clients connected to a hub?)

I'm trying to run/start a task if at least one client is connected, otherwise do not start it:

[HubName("taskActionStatus")] public class TaskActionStatus : Hub, IDisconnect {     static CancellationTokenSource tokenSource;      public void GetTasksStatus(int? siteId)     {         tokenSource = new CancellationTokenSource();         CancellationToken ct = tokenSource.Token;          ITaskRepository taskRepository = UnityContainerSetup.Container.Resolve<ITaskRepository>();          // init task for checking task statuses         var tasksItem = new DownloadTaskItem();         taskRepository.GetTasksStatusAsync(siteId, tasksItem, ct);          // subscribe to event [ listener ]         tasksItem.Changed += new EventHandler<TaskEventArgs>(UpdateTasksStatus);     }      public void UpdateTasksStatus(object sender, TaskEventArgs e)     {         Clients.updateMessages(e.Tasks);     }      // when browsing away from page     public Task Disconnect()     {         try         {             tokenSource.Cancel();         }         catch (Exception)         {             //         }          return null;     } } 

thanks

like image 766
ShaneKm Avatar asked Nov 22 '12 13:11

ShaneKm


People also ask

Is SignalR scalable?

A SignalR app can scale out based on the number of messages sent, while the Azure SignalR Service scales to handle any number of connections.

How long do SignalR connections stay open?

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. Most of the time, such attempts will fail, but in some circumstances they might succeed.


1 Answers

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.

like image 50
Anders Arpi Avatar answered Sep 30 '22 18:09

Anders Arpi