Difference between UserIdentifier, ConnectionId and Groups in SignalR Core

1.7k views Asked by At

I want to understand the philosophy behind UserIdentifier, ConnectionId and Groups in ASP.NET Core SignalR? Isn't it true that same UserIdentifer (represents as user) can have multiple signalR connection IDs? If so why use groups to club connections together? Why not club connections under one UserIdentifier?

1

There are 1 answers

1
Michael Wang On BEST ANSWER

Isn't it true that same UserIdentifer (represents as user) can have multiple signalR connection IDs?

Yes, a single user in SignalR can have multiple connections to an app. For example, a user could be connected on their desktop as well as their phone. Each device has a separate SignalR connection, but they're all associated with the same user.

If so why use groups to club connections together?

A group is a collection of connections associated with a name. Messages can be sent to all connections in a group while each connection can be associated with different users. Groups are the recommended way to send to a connection or multiple connections because the groups are managed by the application. A connection can be a member of multiple groups.


Why not club connections under one UserIdentifier?

You could send a message to a specific user by passing the user identifier to the User function in a hub method, as shown in the following example:

public Task SendPrivateMessage(string user, string message)
{
    return Clients.User(user).SendAsync("ReceiveMessage", message);
}

If a message is sent to the user, all of the connections associated with that user receive the message. The user identifier for a connection can be accessed by the Context.UserIdentifier property in the hub.

  • Clients.Client()
    Calls a method on a specific connected client
  • Clients.User()
    Calls a method on all connections associated with a specific user
  • Clients.Group()
    Calls a method on all connections in the specified group

There are also more methods in Hub.Clients.




SignalR is very flexible and allows many options based on need. You can find more details about users and groups in SignalR here.