Middle
What is SignalR?
sobes.tech AI
Answer from AI
SignalR is a library for ASP.NET Core that enables adding WebSocket and Long Polling functionality to web applications for creating real-time interactive scenarios.
It provides two-way communication between server and client.
Main use cases:
- Chat applications.
- Online games.
- Real-time data updates (e.g., charts, notifications).
- User activity monitoring.
Main components:
- Hubs: Classes that handle incoming client calls and send messages to clients.
- Connections: Represent client connections. They can be established via WebSocket, Server-Sent Events, or Long Polling (depending on client and server support).
Example of creating a hub:
// MyHub.cs
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class MyHub : Hub
{
// Method that can be called by the client
public async Task SendMessage(string user, string message)
{
// Sending message to all connected clients
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
Configuration in Startup.cs:
// In ConfigureServices
services.AddSignalR();
// In Configure
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MyHub>("/myhub"); // Mapping hub to URL
});
On the client side (JavaScript):
// Using npm
// npm install @microsoft/signalr
const hubConnection = new signalR.HubConnectionBuilder()
.withUrl("/myhub") // Hub URL
.build();
// Handling incoming messages from server
hubConnection.on("ReceiveMessage", (user, message) => {
// Logic to process received message
console.log(`${user}: ${message}`);
});
// Opening connection
hubConnection.start()
.then(() => console.log("Connection started"))
.catch(err => console.error(err.toString()));
// Sending message to server
// hubConnection.invoke("SendMessage", "Client", "Hello from client!");
SignalR automatically chooses the optimal transport depending on client and server capabilities, starting with WebSocket and falling back to older protocols if necessary. This ensures broad compatibility.