在 javascript 中调用信号器方法
calling signalr methods in javascript
我正在尝试在我的 .net core 3 Web 应用程序中实现一个部分,该部分实时显示在线用户数。因此,只要用户 joins/leaves 应用程序,计数器就会自动更新而无需刷新页面。
之前我设法获取了使用 Cookies 的活跃用户数。但我试图避免为它刷新页面。我上网了解了 "signalR" 包。
我创建了一个代码部分,可能会获取在线用户数,但我不确定如何在视图/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>();
}
}
我创建了一个单独的静态 class 来捕获 users/ClientIds 的数量。
我在几个论坛上看到过,但是我对如何为.net core 3设置环境感到困惑。
如有任何帮助,我们将不胜感激。
根据你的描述,如果你想在客户端页面显示当前捕获的users/ClientIds个数。我建议你可以尝试调用集线器的方法,在新用户连接时发送更新用户号,并在用户断开连接时发送更新用户号。
更多细节,您可以参考下面的测试演示代码:
1.Add 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.Create 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.Add 客户端视图中的符号参考和 js 代码或 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>
结果:
我正在尝试在我的 .net core 3 Web 应用程序中实现一个部分,该部分实时显示在线用户数。因此,只要用户 joins/leaves 应用程序,计数器就会自动更新而无需刷新页面。
之前我设法获取了使用 Cookies 的活跃用户数。但我试图避免为它刷新页面。我上网了解了 "signalR" 包。
我创建了一个代码部分,可能会获取在线用户数,但我不确定如何在视图/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>();
}
}
我创建了一个单独的静态 class 来捕获 users/ClientIds 的数量。
我在几个论坛上看到过,但是我对如何为.net core 3设置环境感到困惑。
如有任何帮助,我们将不胜感激。
根据你的描述,如果你想在客户端页面显示当前捕获的users/ClientIds个数。我建议你可以尝试调用集线器的方法,在新用户连接时发送更新用户号,并在用户断开连接时发送更新用户号。
更多细节,您可以参考下面的测试演示代码:
1.Add 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.Create 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.Add 客户端视图中的符号参考和 js 代码或 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>
结果: