如何获取特定SignalR Core组中的连接数?
类似的东西:
this.Clients.Group("Something").Count();
如果SendAsync
返回多少个客户端发送消息也将是很好的:
var count = await this.Clients.Client(this.Context.ConnectionId).SendAsync("msg", msg);
我需要这个来确定组是否为空。如果用户强行从SignalR Core断开连接(拔出网线),则数据应该正确。
答案 0 :(得分:1)
您可以使用OnConnected和OnDisconnected事件并保存连接/ connectionIds。
我将类似的信息用于其他信息:
internal static ConcurrentDictionary<string, ConnectionInfos> Users = new ConcurrentDictionary<string, ConnectionInfos>();
public override async Task OnConnectedAsync()
{
var connId = Context.ConnectionId;
if (!Users.Keys.Any(x => x == connId))
{
Users.TryAdd(connId, new ConnectionInfos { /*...*/});
}
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
var id = Context.ConnectionId;
if (Users.TryRemove(id, out ConnectionInfos ci))
{
//Connection removed
}
await base.OnDisconnectedAsync(exception);
}