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

Building a Chat Application Backend

Develop a multi-room messaging system utilizing group-based communication.

In this lesson, you will learn how to architect a multi-room messaging system by leveraging SignalR’s Groups functionality to segregate communication streams.

Beyond Global Broadcasting

In a chat application, broadcasting every message to every connected client is inefficient and a privacy nightmare. Instead, we use Group-based communication. Think of a "Room" as a virtual partition; when a user joins a room, their connection ID is mapped to a specific group name within the SignalR backplane.

Managing Group Membership

SignalR provides Groups.AddToGroupAsync and Groups.RemoveFromGroupAsync methods to manage these memberships. The key to a robust backend is ensuring these operations are atomic and synced with your persistence layer (like a database).

Here is how you would implement a join-room flow within your Hub:

public class ChatHub : Hub
{
    public async Task JoinRoom(string roomName)
    {
        // Add the current connection to the group
        await Groups.AddToGroupAsync(Context.ConnectionId, roomName);
        
        // Notify others in the room
        await Clients.Group(roomName).SendAsync("UserJoined", Context.User.Identity.Name);
    }

    public async Task SendMessage(string roomName, string message)
    {
        // Only broadcast to clients in the specified group
        await Clients.Group(roomName).SendAsync("ReceiveMessage", Context.User.Identity.Name, message);
    }
}

Architectural Considerations

When building this, remember that Groups are not automatically persisted. If a server node restarts, you rely on the Redis Backplane (which you learned previously) to propagate these group memberships across your horizontally scaled instances.

Furthermore, you should implement OnDisconnectedAsync to automatically remove users from their active groups. This keeps your memory footprint clean and prevents "ghost" users from receiving messages long after they have closed their browser window. Because SignalR groups are ephemeral, always validate that the user is authorized to be in the group they are attempting to join or message, ensuring that your application's logic prevents users from "spying" on private rooms they haven't been granted access to.

Key Takeaway: Use SignalR Groups as ephemeral partitions to decouple message delivery, ensuring that your backend only routes traffic to the relevant subset of connected clients.