From your description, it appears that each of your workers is connected to SignalR as a client. So the generated ConnectionId
are different, from the actual development, it is also like this, a real user, may open multiple web pages to establish a connection with the SignalR Hub.
We usually need to use ConcurrentDictionary
to save information about connected users. For more details, you can check my answer in this thread.
The different is you are using C# client, that is using javascript client. But managing connected users in Signalr Hub, this is consistent.
public partial class MainHub : Hub
{
public static ConcurrentDictionary<string?, List<string>>? ConnectedUsers;
public MainHub()
{
ConnectedUsers = new ConcurrentDictionary<string?, List<string>>();
}
public override async Task OnConnectedAsync()
{
//// Get HttpContext In asp.net core signalr
//IHttpContextFeature hcf = (IHttpContextFeature)this.Context.Features[typeof(IHttpContextFeature)];
//HttpContext hc = hcf.HttpContext;
//string uid = hc.Request.Path.Value.ToString().Split(new string[] { "/", "" }, StringSplitOptions.RemoveEmptyEntries)[1].ToString();
string? userid = Context.User?.Identity?.Name;
if (userid == null || userid.Equals(string.Empty))
{
Trace.TraceInformation("user not loged in, can't connect signalr service");
return;
}
Trace.TraceInformation(userid + "connected");
// save connection
List<string>? existUserConnectionIds;
ConnectedUsers.TryGetValue(userid, out existUserConnectionIds);
if (existUserConnectionIds == null)
{
existUserConnectionIds = new List<string>();
}
existUserConnectionIds.Add(Context.ConnectionId);
ConnectedUsers.TryAdd(userid, existUserConnectionIds);
//await Clients.All.SendAsync("ServerInfo", userid, userid + " connected, connectionId = " + Context.ConnectionId);
await base.OnConnectedAsync();
}
}