SignalR library in ASP.NET
SignalR is a library for ASP.NET that simplifies the process of adding real-time web functionality to applications. Real-time web functionality allows server-side code to push content to clients instantly, rather than having the server wait for a client to request new data.
Key Features of SignalR
- Real-Time Communication: Enables real-time bi-directional communication between server and client.
- Persistent Connections: Uses WebSockets as the underlying protocol when available and falls back to other techniques like Server-Sent Events (SSE) or Long Polling when necessary.
- Automatic Reconnection: Automatically reconnects clients that are temporarily disconnected.
- Scalability: Can be scaled out using the Redis, SQL Server, or Azure Service Bus backplanes.
- Client Libraries: Supports multiple client platforms, including JavaScript for web applications, .NET clients, and even mobile platforms.
How SignalR Works
SignalR uses a concept called "Hubs" to establish a communication channel between the client and the server. Hubs are high-level pipelines that allow the client and server to call methods on each other directly.
Example Usage of SignalR
Server-Side (ASP.NET Core)
-
Install SignalR Package:
dotnet add package Microsoft.AspNetCore.SignalR
-
Create a Hub Class:
using Microsoft.AspNetCore.SignalR; public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } }
-
Configure SignalR in Startup.cs:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub<ChatHub>("/chathub"); }); } }
Client-Side (JavaScript)
-
Add SignalR Client Library:
Include the SignalR client library in your HTML file.
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7/signalr.min.js"></script>
-
Connect to the Hub and Send/Receive Messages:
<!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <div> <input type="text" id="userInput" placeholder="Name" /> <input type="text" id="messageInput" placeholder="Message" /> <button onclick="sendMessage()">Send</button> </div> <ul id="messagesList"></ul> <script> 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().catch(err => console.error(err.toString())); function sendMessage() { const user = document.getElementById("userInput").value; const message = document.getElementById("messageInput").value; connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString())); } </script> </body> </html>
Use Cases for SignalR
- Chat Applications: Real-time chat applications where messages are instantly broadcast to all connected users.
- Live Notifications: Real-time notifications for events such as new messages, alerts, or updates.
- Collaborative Tools: Applications where multiple users need to collaborate in real-time, such as whiteboards or collaborative document editing.
- Live Dashboards: Real-time data dashboards for monitoring applications, business metrics, or server health.
Published on: Jul 06, 2024, 07:02 AM