gpt4 book ai didi

asp.net-mvc-4 - 检查SignalR组是否为空?

转载 作者:行者123 更新时间:2023-12-02 03:43:09 25 4
gpt4 key购买 nike

在OnConnected方法中,客户端被添加到带有他的名字的组中(组包含所有客户端ID),然后他的名字被添加到列表中(如果不存在)。

static List<string> onlineClients = new List<string>(); // list of clients names

public override Task OnConnected()
{
Groups.Add(Context.ConnectionId, Context.User.Identity.Name);

if (!onlineClients.Exists(x => x == Context.User.Identity.Name))
{
onlineClients.Add(Context.User.Identity.Name);
}

return base.OnConnected();
}

在 OnDisconnected 方法中,我试图测试该组是否为空以从列表中删除元素。但删除最后一个连接后,该组不为空。

public override Task OnDisconnected(bool stopCalled)
{
if (stopCalled)
{
// We know that Stop() was called on the client,
// and the connection shut down gracefully.

Groups.Remove(Context.ConnectionId, Context.User.Identity.Name);

if (Clients.Group(Context.User.Identity.Name) == null)
{
onlineClients.Remove(Context.User.Identity.Name);
}

}
return base.OnDisconnected(stopCalled);
}

我可以检查空组吗?

最佳答案

我认为这对你的问题的答复有点晚了,也许你已经忘记了:d

我使用包含组名称(User.Identity.Name)及其客户编号的字典解决了我的问题,如下所示。

private static Dictionary<string, int> onlineClientCounts  = new Dictionary<string, int>();

public override Task OnConnected()
{
var IdentityName = Context.User.Identity.Name;
Groups.Add(Context.ConnectionId, IdentityName);

int count = 0;
if (onlineClientCounts.TryGetValue(IdentityName, out count))
onlineClientCounts[IdentityName] = count + 1;//increment client number
else
onlineClientCounts.Add(IdentityName, 1);// add group and set its client number to 1

return base.OnConnected();
}

public override Task OnDisconnected(bool stopCalled)
{
var IdentityName = Context.User.Identity.Name;
Groups.Remove(Context.ConnectionId, IdentityName);

int count = 0;
if (onlineClientCounts.TryGetValue(IdentityName, out count))
{
if (count == 1)//if group contains only 1client
onlineClientCounts.Remove(IdentityName);
else
onlineClientCounts[IdentityName] = count - 1;
}

return base.OnDisconnected(stopCalled);
}

关于asp.net-mvc-4 - 检查SignalR组是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25957312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com