SignalR is a real-time communication library from Microsoft that lets a server instantly push updates to connected clients (like web browsers, mobile apps, or desktop apps).
In simple terms
Instead of a client repeatedly asking the server, “Anything new?”, SignalR allows the server to say, “Hey, here’s new data right now!” — instantly.
What it’s used for
SignalR is commonly used in apps that need live updates, such as:
- Chat applications (like messaging apps)
- Live dashboards (stocks, analytics)
- Online gaming
- Notifications (alerts, updates)
- Collaborative tools (shared editing)
How it works (conceptually)
SignalR manages the connection between client and server using the best available method:
- WebSockets (fastest, if supported)
- Server-Sent Events
- Long polling (fallback)
You don’t have to worry about which one—it handles that automatically.
Example scenario
Imagine a chat app:
- User A sends a message
- The server receives it
- SignalR immediately pushes that message to User B (no refresh needed)
Where it fits
SignalR is part of the ASP.NET ecosystem and works especially well with .NET applications, though clients can be written in JavaScript, C#, and more.
Key benefits
- Real-time communication
- Handles connection management for you
- Scales with cloud services
- Works across platforms
1. Install SignalR
SignalR is already included in modern ASP.NET Core, but if needed:
dotnet add package Microsoft.AspNetCore.SignalR
⚡ 2. Create a Hub (Server-side)
A Hub is the core class that handles communication.
using Microsoft.AspNetCore.SignalR;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
// Send message to all connected clients
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
⚙️ 3. Configure in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
var app = builder.Build();
app.MapHub<ChatHub>("/chatHub");
app.Run();
🌐 4. Client-side (JavaScript)
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>
<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
// Receive message from server
connection.on("ReceiveMessage", (user, message) => {
console.log(user + ": " + message);
});
// Start connection
connection.start().then(() => {
console.log("Connected");
// Send message to server
connection.invoke("SendMessage", "Shiva", "Hello SignalR!");
});
</script>
🔁 How this works
-
Client connects to
/chatHub -
Client calls
SendMessage - Server (Hub) receives it
-
Server broadcasts via
ReceiveMessage - All clients instantly get the message
🎯 Output
Shiva: Hello SignalR!
0 Comments
POST Answer of Questions and ASK to Doubt