Search code examples
signalrsignalr-hubasp.net-core-3.0signalr.clientasp.net-core-signalr

calling signalr methods in javascript


I am trying to implement a segment in my .net core 3 web application that shows the number of online users in real-time. So the counter gets updated automatically without page refresh anytime a user joins/leaves the application.

Previously I managed to get the number of active users using Cookies. But I was trying to avoid the page refresh for it. I went online and came to know about "signalR" package.

I have created a code part that might get the number of online users but I am not at sure how to show it on a View/ Html page.

Here is what I tried -

namespace Project.HubSignal
{
    public class ChatHub : Hub
    {
        public override Task OnConnectedAsync()
        {
            UserHandler.connectedIds.Add(Context.ConnectionId);
            return base.OnConnectedAsync();
        }

    }

    public static class UserHandler
    {
        public static HashSet<string> connectedIds = new HashSet<string>();

    }

}

I have created a separate static class to capture the number of users/ClientIds.

I have seen on a few forums, but I got confused about how to set up the environment for .net core 3.

Any help would be appreciated.


Solution

  • According to your description, if you want to show the current captured the number of users/ClientIds in the client page. I suggest you could try to call the hub's method to send update user number when the new user connected and send the update user number when the user disconnected.

    More details, you could refer to below test demo codes:

    1.Add Signalr service and add endpoint mapping:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddSignalR();
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
    
            app.UseHttpsRedirection();
            app.UseStaticFiles();
    
            app.UseRouting();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapHub<UserActivityHub>("/active");
    
    
            });
        }
    

    2.Create the activehun and call send usernum in OnConnectedAsync and method

    public class UserActivityHub: Hub
    {
        public static int UserNum;
    
        public void SendUserList(int userNum)
        {
          Clients.All.SendAsync("broadcastMessage", userNum.ToString());
        }
    
        public override Task OnConnectedAsync()
        {
            UserNum = UserNum + 1;
            // Send the current users
            SendUserList(UserNum);
    
            return base.OnConnectedAsync();
        }
    
    
        public override Task OnDisconnectedAsync(Exception exception)
        {
            UserNum = UserNum - 1;
            // Send the current users
            SendUserList(UserNum);
            return base.OnDisconnectedAsync(exception);
        }
    }
    

    3.Add signlar reference and js codes in the client view or html.

    <body>
        <div class="container">
    
            <span id="usernum"></span>
        </div>
        <!--Script references. -->
        <!--Reference the SignalR library. -->
        <script type="text/javascript" src="lib/signalr.min.js"></script>
        <!--Add script to update the page and send messages.-->
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function () {
    
                // Start the connection.
                var connection = new signalR.HubConnectionBuilder()
                    .withUrl('/active')
                                    .build();
    
                // Create a function that the hub can call to broadcast messages.
                connection.on('broadcastMessage', function (userNum) {
    
                    document.getElementById('usernum').innerHTML = userNum ;
                });
    
                // Transport fallback functionality is now built into start.
                connection.start()
                    .then(function () {
                        console.log('connection started');
                })
                .catch(error => {
                    console.error(error.message);
                });
            });
        </script>
    </body>
    

    Result:

    enter image description here