How can I get online and offline users using signalR?

Viewed 217

I have already working and simple code to get the number of users using SIGNALR. I'm new with using it.

All I need now is to get a list of online users and offline users.

here is my code

OnlineCountHub.cs

public class OnlineCountHub : Hub
{
    private static int Count = 0;
    public override async Task OnConnectedAsync()
    {
        var u = Context.User.Identity;
        var result = u.IsAuthenticated ? u.Name : "";

        var claims = Context.User.Claims.ToList();
        foreach (var user in claims)
        {
            //await Groups.AddToGroupAsync(Context.ConnectionId, user.Value);
            // await Groups.AddToGroupAsync("ConectedUsers-ConnectionId", "ConnectedUsers-GroupName");
            // await Groups.AddToGroupAsync("UNConectedUsers-ConnectionId", "UNConnectedUsers-GroupName");
        }
        Count++;

        await base.OnConnectedAsync();
        await Clients.User("9b9ff00d-6de4-4487-9f00-99bd7f3aa345").SendAsync("updateCount", Count);

        //return Task.CompletedTask;
    }
    public override async Task OnDisconnectedAsync(Exception exception)
    {
        //var claims = Context.User.Claims.ToList();   
        //foreach (var user in claims)
        //{
        //    await Groups.RemoveFromGroupAsync(Context.ConnectionId, user.Value);
        //}

        Count--;
        await base.OnDisconnectedAsync(exception);
        await Clients.User("9b9ff00d-6de4-4487-9f00-99bd7f3aa345").SendAsync("updateCount", Count);
     
        //return Task.CompletedTask;
    }
}

onlinecount.js

let onlineCount = document.querySelector('span.online-count');
let updateCountCallback = function (message) {
if (!message) return;
console.log('updateCount = ' + message);
if (onlineCount) onlineCount.innerText = message;
};

function onConnectionError(error) {
    if (error && error.message) console.error(error.message);
}

let countConnection = new signalR.HubConnectionBuilder().withUrl('/onlinecount').build();
countConnection.on('updateCount', updateCountCallback);
countConnection.onclose(onConnectionError);
countConnection.start()
.then(function () {
    console.log('OnlineCount Connected');
})
.catch(function (error) {
    console.error(error.message);
});

Don't forget

Startup.cs [ConfigureServices]
if (EnableSignalR) services.AddSignalR();
Startup.cs [Configure]
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            if (EnableSignalR) 
                endpoints.MapHub<OnlineCountHub>("/onlinecount");
        });
layout or index
@if (Startup.EnableSignalR)
{
    <strong class="text-warning ps-3 mt-3 text-white">Online(<span class="online-count"></span>)</strong>
}
@if (Startup.EnableSignalR)
{
    <script src="~/SignalR/signalRlibs/signalr.js"></script>
    <script src="~/SignalR/onlinecount.js"></script>
}

Now .. how to pass to the view list of online users and list of offline users ?

0 Answers
Related