SignalR Real-Time Communication
SignalR abstracts WebSockets, Server-Sent Events, and Long Polling into a single real-time communication library. Build live chat, dashboards, notifications, and collaborative features with minimal boilerplate.
40 min•By Priygop Team•Last updated: Feb 2026
SignalR Code
Example
// Hub definition
[Authorize]
public class ChatHub : Hub {
public async Task SendMessage(string message) {
var user = Context.User?.Identity?.Name ?? "Anonymous";
// Broadcast to ALL connected clients
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
public async Task JoinRoom(string roomName) {
await Groups.AddToGroupAsync(Context.ConnectionId, roomName);
await Clients.Group(roomName).SendAsync("UserJoined", Context.User?.Identity?.Name);
}
public async Task SendToRoom(string roomName, string message) {
// Only send to users in this group
await Clients.Group(roomName).SendAsync("ReceiveMessage",
Context.User?.Identity?.Name, message);
}
public override async Task OnConnectedAsync() {
await Clients.Others.SendAsync("UserConnected", Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? ex) {
await Clients.Others.SendAsync("UserDisconnected", Context.ConnectionId);
await base.OnDisconnectedAsync(ex);
}
}
// Program.cs
builder.Services.AddSignalR()
.AddStackExchangeRedis("localhost:6379"); // Scale-out across servers
app.MapHub<ChatHub>("/hubs/chat");
// JavaScript client (npm install @microsoft/signalr)
// const connection = new signalR.HubConnectionBuilder()
// .withUrl("/hubs/chat", { accessTokenFactory: () => getJwtToken() })
// .withAutomaticReconnect()
// .build();
// await connection.start();
// connection.on("ReceiveMessage", (user, msg) => displayMessage(user, msg));
// await connection.invoke("SendMessage", "Hello everyone!");