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! 🎯
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. 💡
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. 📝
dotnet new webapi -n SignalRChat
cd SignalRChatdotnet add package Microsoft.AspNetCore.SignalRHubs and create a new class called ChatHub inside it.using Microsoft.AspNetCore.SignalR;
namespace SignalRChat.Hubs
{
public class ChatHub : Hub
{
// Implementation goes here
}
}ChatHub class, create a method to add a client to a group.public async Task JoinGroup(string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
}public async Task SendMessage(string groupName, string message)
{
await Clients.Group(groupName).SendAsync("ReceiveMessage", message);
}public async Task BroadcastMessage(string message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}ChatHub class.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.");
}Startup class to add the hub to the services and configure it for CORS.services.AddSignalR();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
});Configure method of the Startup class.app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());dotnet runNow, you can test your SignalR application by connecting multiple clients and sending group messages using JavaScript in the browser. ✅
Which method sends a message to all connected clients?
Stay tuned for more exciting lessons on ASP.NET and SignalR! 🚀