用javascript调用信号方法

问题描述 投票:0回答:1

我正在尝试在.net core 3 Web应用程序中实现一个段,该段实时显示在线用户数量。因此,只要用户加入/离开应用程序,计数器就会自动更新而无需刷新页面。

[以前,我设法使用Cookie来获得活跃用户的数量。但是我试图避免刷新页面。我上网了,了解了“ signalR”软件包。

我创建了一个代码部分,它可能会获得在线用户的数量,但是我不确定如何在View / Html页面上显示它。

这是我尝试过的-

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

    }

}

我创建了一个单独的静态类来捕获用户/ ClientId的数量。

我在一些论坛上看到过,但是我对如何为.net core 3设置环境感到困惑。

任何帮助将不胜感激。

signalr signalr-hub asp.net-core-3.0 signalr.client asp.net-core-signalr
1个回答
1
投票

根据您的描述,如果要显示当前捕获的客户端页面中用户/客户端ID的数量。我建议您可以尝试调用集线器的方法,以在新用户连接时发送更新用户号,并在用户断开连接时发送更新用户号。

更多详细信息,您可以参考下面的测试演示代码:

1。添加Signalr服务并添加端点映射:

    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。创建Activehun并在OnConnectedAsync和方法中调用send usernum发送

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。在客户端视图或html中添加信号引用和js代码。

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

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.