Course contentsShow
← C#
Lesson 1447 of 1,90813. Real-time Communication with SignalRFree lesson

Message Broadcasting Scopes

Distribute messages to individual clients, connection groups, or the entire broadcast pool.

In this lesson, you will learn how to precisely target your SignalR communications by choosing between global broadcasts, connection-specific messaging, and logical group partitions.

When building real-time applications, sending data to every connected client is rarely the most efficient approach. SignalR provides three primary "scopes" to control the distribution of messages, allowing you to optimize bandwidth and maintain data privacy.

The Three Scopes of Communication

1. The Global Broadcast (Clients.All)

This scope sends a message to every single client connected to the hub. It is useful for system-wide announcements, such as "Server going down for maintenance" or global notifications. Use this sparingly, as it scales poorly if you have thousands of concurrent users who don't need the specific update.

2. The Connection-Specific Target (Clients.Client)

Sometimes you need to talk to one specific user, such as sending a private notification or a direct confirmation. By using a unique ConnectionId, you can isolate a message to a single device session:

public async Task SendPrivateMessage(string connectionId, string message)
{
    await Clients.Client(connectionId).SendAsync("ReceivePrivateMessage", message);
}

3. The Group Broadcast (Clients.Group)

This is the most common pattern for scaling apps. Instead of managing individual connections, you add them to a logical "Group" (e.g., ChatRoom_123 or Project_Alpha). When you broadcast to a group, only clients currently associated with that label receive the packet:

public async Task JoinRoom(string roomName)
{
    await Groups.AddToGroupAsync(Context.ConnectionId, roomName);
    await Clients.Group(roomName).SendAsync("UserJoined", Context.ConnectionId);
}

Choosing Your Scope

Think of these scopes as a hierarchy of precision. Use Clients.All for universal status updates, Clients.Client for personalized security-sensitive data, and Clients.Group for managing shared state among subsets of users. By partitioning your traffic into groups, you keep the server-side logic clean and ensure that the SignalR engine only transmits data to the clients that actually need to process it, significantly improving the performance of your real-time infrastructure.

Key Takeaway: Control your traffic overhead by choosing between global broadcasts, direct connection targeting, and logical grouping to ensure messages reach only the intended recipients.