Loading...

Real-time Communication with SignalR in ASP.NET Core

Real-time Communication with SignalR in ASP.NET Core

ASP.NET Core SignalR is an open-source library that simplifies adding real-time web functionality to applications. Real-time web functionality enables server-side code to push content to connected clients instantly as it becomes available, rather than the server waiting for a client to request new data.

Common Use Cases for SignalR:

  • Live chat applications
  • Real-time dashboards and monitoring tools
  • Multiplayer games
  • Collaborative applications (e.g., whiteboards, document editing)
  • Push notifications

Setting up SignalR Hub in ASP.NET Core

First, create a Hub class that inherits from Hub and defines methods that clients can call and methods that the server can call on clients:

using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } public override async Task OnConnectedAsync() { Console.WriteLine($"Client connected: {Context.ConnectionId}"); await Clients.All.SendAsync("UserConnected", Context.ConnectionId); await base.OnConnectedAsync(); } public override async Task OnDisconnectedAsync(Exception? exception) { Console.WriteLine($"Client disconnected: {Context.ConnectionId}"); await Clients.All.SendAsync("UserDisconnected", Context.ConnectionId); await base.OnDisconnectedAsync(exception); } }

Then, configure SignalR in your Program.cs (or Startup.cs):

var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddSignalR(); builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapHub("/chatHub"); // Map your SignalR Hub app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();

Client-side Integration (JavaScript)

On the client-side, you'll use the SignalR JavaScript client library:

const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .build(); connection.on("ReceiveMessage", (user, message) => { const li = document.createElement("li"); li.textContent = `${user}: ${message}`; document.getElementById("messagesList").appendChild(li); }); connection.start().then(() => { console.log("SignalR Connected."); document.getElementById("sendButton").addEventListener("click", () => { const user = document.getElementById("userInput").value; const message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(err => console.error(err)); }); }).catch(err => console.error(err));

Conclusion

SignalR provides a robust and easy-to-use framework for adding real-time capabilities to your ASP.NET Core applications. Whether you're building a simple chat or a complex collaborative tool, SignalR simplifies the complexities of real-time communication.

Comments

Leave a comment

No comments yet. Be the first to share your thoughts!