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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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);
    }
}

Method 3

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 (:

Method 4

Now you need:

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);
}

Method 5

I would like to add that if you are using a serverless solution with Azure Functions and Azure SignalR Service there is the following resolved issue: https://github.com/Azure/azure-functions-signalrservice-extension/issues/54

It refers to this sample where you can use Event Grids to get the real-time count of connections, pretty sweet. https://github.com/aspnet/AzureSignalR-samples/tree/master/samples/EventGridIntegration

Method 6

In my project which use Microsoft.AspNetCore.SignalR.Core version 1.1.0

I can debug and see the count with

((Microsoft.AspNetCore.SignalR.DefaultHubLifetimeManager<XXX.Push.SignalR.EventHub>)((Microsoft.AspNetCore.SignalR.Internal.AllClientProxy<XXX.Push.SignalR.EventHub>)((Microsoft.AspNetCore.SignalR.TypedClientBuilder.IEventImpl)((Microsoft.AspNetCore.SignalR.Internal.HubClients<XXX.Push.SignalR.EventHub, XXX.Push.SignalR.IEvent>)_hub.Clients).All)._proxy)._lifetimeManager)._connections.Count

It looks like this:

Get number of listeners, clients connected to SignalR hub


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x