Signalr 返回信号器中已连接客户端的计数。不启动客户端功能
我正在尝试使用SignalR返回到web客户端的所有连接的计数。我通过在hubSignalr 返回信号器中已连接客户端的计数。不启动客户端功能,signalr,Signalr,我正在尝试使用SignalR返回到web客户端的所有连接的计数。我通过在hubOnConnected()方法上触发逻辑来增加并保持客户端计数 public class PopHub : Hub { public static List<string> Users = new List<string>(); public override Task OnConnected() { var clientId = GetClientI
OnConnected()
方法上触发逻辑来增加并保持客户端计数
public class PopHub : Hub
{
public static List<string> Users = new List<string>();
public override Task OnConnected()
{
var clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
Send(Users.Count);
return base.OnConnected();
}
public void Send(int count)
{
Clients.All.updateUsersOnlineCount(count);
}
最后是生成的js中的代码片段
proxies.popHub = this.createHubProxy('popHub');
proxies.popHub.client = { };
proxies.popHub.server = {
popClient: function (message) {
return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["PopClient"], $.makeArray(arguments)));
},
query: function () {
return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["Query"], $.makeArray(arguments)));
},
send: function (count) {
return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["Send"], $.makeArray(arguments)));
}
};
**请注意,
Popclient
和Query
是不相关的服务器端事件,这些事件确实可以让我进行某种程度的健全性检查。你知道为什么我的客户端updateUsersOnlineCount
函数没有像我期望的那样记录连接数吗?请尝试一下,可能是Base.OnConnected尚未执行,因此它还没有准备好向客户端广播
//Client
$.connection.hub.start().done(function() {
console.log('connected');
hub.server.ClientCount();
});
//Hub
public static List<string> Users = new List<string>();
public override Task OnConnected()
{
var clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
//Send(Users.Count); //not calling this since it's not working
return base.OnConnected();
}
public void ClientCount()
{
Clients.All.updateUsersOnlineCount(Users.Count);
}
//客户端
$.connection.hub.start().done(函数()){
console.log('connected');
hub.server.ClientCount();
});
//枢纽
公共静态列表用户=新列表();
已连接的公用覆盖任务()
{
var clientId=GetClientId();
if(Users.IndexOf(clientId)=-1)
{
Users.Add(clientId);
}
//Send(Users.Count);//不调用它,因为它不工作
返回base.OnConnected();
}
public void ClientCount()
{
Clients.All.updateUsersOnlineCount(Users.Count);
}
太好了,我将在周一回到我的源代码时尝试一下。谢谢这可能不是导致updateUsersOnlineCount
无法登录的原因,但您不应该修改OnConnected中的静态列表。在System.collections.Generic命名空间中找到的集合不是线程安全的。而是使用System.Collections.Concurrent命名空间中的集合,例如。
//Client
$.connection.hub.start().done(function() {
console.log('connected');
hub.server.ClientCount();
});
//Hub
public static List<string> Users = new List<string>();
public override Task OnConnected()
{
var clientId = GetClientId();
if (Users.IndexOf(clientId) == -1)
{
Users.Add(clientId);
}
//Send(Users.Count); //not calling this since it's not working
return base.OnConnected();
}
public void ClientCount()
{
Clients.All.updateUsersOnlineCount(Users.Count);
}