17. SignalR with Groups

SignalR with Groups in .NET Core

Introduction to SignalR

SignalR is a free and open-source software library for Microsoft ASP.NET that allows server code to send asynchronous notifications to client-side web applications. The library includes server-side and client-side JavaScript libraries.

Understanding Groups in SignalR

Groups in SignalR provide a method for broadcasting messages to specific users. You can add and remove connections to groups in your Hub class. SignalR takes care of all of the details for you.

Key Points:

Using Groups in SignalR

Here's a simple example of how to use groups in a SignalR Hub:

public class ChatHub : Hub
{
    public Task JoinGroup(string groupName)
    {
        return Groups.AddToGroupAsync(Context.ConnectionId, groupName);
    }

    public Task LeaveGroup(string groupName)
    {
        return Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
    }

    public Task SendMessageToGroup(string groupName, string message)
    {
        return Clients.Group(groupName).SendAsync("ReceiveMessage", message);
    }
}

In this example, JoinGroup and LeaveGroup methods are used to add and remove connections to groups. The SendMessageToGroup method sends a message to all connections in a specified group.

Working with SignalR Groups in a Real-Time Chat App

Consider a real-time chat application where you want to send a message to all users in a particular chat room. Here's a more detailed example:

public class ChatHub : Hub
{
    public async Task JoinRoom(string roomName)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, roomName);

        await Clients.Group(roomName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} has joined the room");
    }

    public async Task LeaveRoom(string roomName)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, roomName);

        await Clients.Group(roomName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} has left the room");
    }

    public async Task SendMessageToRoom(string roomName, string message)
    {
        await Clients.Group(roomName).SendAsync("ReceiveMessage", message);
    }
}

In this example, when a user joins a room, a message is sent to all users in the room informing them of the new member. Similarly, when a user leaves a room, a message is broadcasted to all remaining users. When a user sends a message, it is broadcasted to all users in the room.

Summary

SignalR groups provide a powerful feature for sending real-time updates to specific groups of connected clients. This feature is essential in scenarios like chat rooms where updates need to be broadcasted to specific groups of clients.

Reference

The content in this document is based on the original notes provided in Azerbaijani. For further details, you can refer to the original document using the following link:

Original Note - Azerbaijani Version