signalr
  1. signalr-grouping-connections

Grouping Connections - SignalR Hubs

Syntax

var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
hubContext.Groups.Add(Context.ConnectionId, "groupName");
hubContext.Groups.Remove(Context.ConnectionId, "groupName");

Example

public class ChatHub : Hub
{
    public async Task JoinGroup(string groupName)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
        await Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} has joined the group {groupName}.");
    }

    public async Task LeaveGroup(string groupName)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
        await Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} has left the group {groupName}.");
    }

    public async Task SendMessageToGroup(string groupName, string message)
    {
        await Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId}: {message}");
    }
}

Output

Client A: JoinGroup("GroupA")
Server: Client A has joined the group GroupA.

Client B: JoinGroup("GroupA")
Server: Client B has joined the group GroupA.

Client A: SendMessageToGroup("GroupA", "Hello from A!")
Server: Client A: Hello from A!

Client B: SendMessageToGroup("GroupA", "Hello from B!")
Server: Client B: Hello from B!

Explanation

SignalR Hubs allow for grouping of connections so that messages can be sent to subsets of the connected clients. Groups.AddToGroupAsync and Groups.RemoveFromGroupAsync methods add and remove a connection from a specified group. Clients.Group method broadcasts messages to all clients that belong to a specified group.

Use

Grouping connections is useful for scenarios where messages need to be sent to subsets of the connected clients. Examples include chat applications, multiplayer games, and real-time collaboration tools.

Important Points

  • Only authenticated connections can be added to groups.
  • Connection IDs may change over time so it's important to use the Context.ConnectionId property to obtain the correct connection ID when adding or removing a connection from a group.

Summary

SignalR Hubs provide the ability to group connections which enables sending messages to subsets of connected clients. Syntax involves the use of Groups.AddToGroupAsync and Groups.RemoveFromGroupAsync methods to add and remove connections from groups and Clients.Group method to broadcast messages to specific groups. Grouping connections is useful for chat applications, multiplayer games, and real-time collaboration tools. It's important to note that only authenticated connections can be added to groups and connection IDs may change over time.

Published on: