C#C
C#10mo ago
WhiteCharun

✅ [SignalR] How to effeciently keep track of ConnectionIds.

I'm currently trying to build a little chat room where users can send messages. The thing I can't get over my head is if this is the best way to keep track of connection Ids. Since there could be multiple tabs open i want to send the message to all the tabs so I need to make a persistant layer where I associate an id and username with the connection Id of signalR. On the client side as soon as i connect to the websocket server i call the RegisterUser
public class ChatHub : Hub
{
    private readonly IConnectionManager _connectionManager;

    public ChatHub(IConnectionManager connectionManager)
    {
        _connectionManager = connectionManager;
    }

    public async Task SendMessage(UserChatHubDTO user, string message)
    {

        await Clients.All.SendAsync("ReceiveMessage", user, message);

    }
    public void RegisterUser(UserChatHubDTO user)
    {
        _connectionManager.AddConnection(Context.ConnectionId, user);
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        _connectionManager.RemoveConnection(Context.ConnectionId);
        await base.OnDisconnectedAsync(exception);
    }
} 
Was this page helpful?