ASP .NET Tutorial: Groups in SignalR

beginner
7 min

ASP .NET Tutorial: Groups in SignalR

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of ASP.NET and exploring the power of Groups in SignalR. Let's get started! 🎯

What is SignalR?

SignalR is a library that simplifies the process of adding real-time web functionality to ASP.NET applications. It enables bi-directional communication between the server and the client, allowing for instant updates and notifications. 💡

What are Groups in SignalR?

Groups in SignalR allow you to categorize clients for targeted communication. This means you can send messages to specific clients, groups of clients, or all connected clients. 📝

Setting Up the Project

  1. Create a new ASP.NET Core Web Application.
sh
dotnet new webapi -n SignalRChat cd SignalRChat
  1. Install the SignalR package.
sh
dotnet add package Microsoft.AspNetCore.SignalR

Creating a Hub

  1. Add a new folder named Hubs and create a new class called ChatHub inside it.
csharp
using Microsoft.AspNetCore.SignalR; namespace SignalRChat.Hubs { public class ChatHub : Hub { // Implementation goes here } }

Implementing Groups

  1. In the ChatHub class, create a method to add a client to a group.
csharp
public async Task JoinGroup(string groupName) { await Groups.AddToGroupAsync(Context.ConnectionId, groupName); }
  1. Create a method to send a message to a specific group.
csharp
public async Task SendMessage(string groupName, string message) { await Clients.Group(groupName).SendAsync("ReceiveMessage", message); }
  1. Implement a method to broadcast a message to all connected clients.
csharp
public async Task BroadcastMessage(string message) { await Clients.All.SendAsync("ReceiveMessage", message); }

Running the Application

  1. Add a new method to handle client connections and disconnections in the ChatHub class.
csharp
public override async Task OnConnectedAsync() { await Groups.AddToGroupAsync(Context.ConnectionId, "AllUsers"); await BroadcastMessage($"{Context.ConnectionId} joined the chat."); } public override async Task OnDisconnectedAsync(Exception exception) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, "AllUsers"); await BroadcastMessage($"{Context.ConnectionId} left the chat."); }
  1. Update the Startup class to add the hub to the services and configure it for CORS.
csharp
services.AddSignalR(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub<ChatHub>("/chatHub"); });
  1. Configure CORS by adding the following code in the Configure method of the Startup class.
csharp
app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader());
  1. Run the application.
sh
dotnet run

Now, you can test your SignalR application by connecting multiple clients and sending group messages using JavaScript in the browser. ✅

Quiz Time!

Quick Quiz
Question 1 of 1

Which method sends a message to all connected clients?

Stay tuned for more exciting lessons on ASP.NET and SignalR! 🚀