What is ASP.NET Core SignalR?
ASP.NET Core SignalR is a library for ASP.NET Core developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality enables server-side code to push content to connected clients instantly as new data becomes available, rather than waiting for a client to request new data by polling.
Key Features
- Real-time Communication: Enables server-side code to push content to clients instantly.
- Cross-Platform Support: Works across various platforms and devices.
- Abstraction over Transports: Handles different underlying transport mechanisms like WebSockets, Server-Sent Events (SSE), and Long Polling.
- Hubs: Provides a high-level abstraction to build real-time experiences. A Hub can send messages to all connected clients, to specific clients, or to groups of clients.
- Client Libraries: Available for JavaScript and .NET clients.
When to Use SignalR
SignalR is ideal for applications that require:
- Real-time updates (e.g., live dashboards, stock tickers, sports scores).
- Collaborative applications (e.g., shared whiteboards, multi-user editors).
- Live notifications (e.g., chat applications, social media feeds).
- Games that require constant updates between server and clients.
How SignalR Works
SignalR uses a technique called "abstraction over transport." This means that SignalR connects clients and servers using the best available transport method. The primary transport is WebSockets. If WebSockets are not available, SignalR falls back to other transports. The available transports are:
- WebSockets: A full-duplex communication channel over a single TCP connection. This is the preferred transport.
- Server-Sent Events (SSE): A unidirectional transport that allows the server to push data to the client over HTTP.
- Long Polling: A technique where the client makes a request to the server, and the server holds the connection open until it has new information to send, or the connection times out.
SignalR negotiates the best available transport automatically. Developers typically interact with SignalR through a concept called a "Hub."
Getting Started with SignalR
To get started with SignalR, you'll need to:
- Install the necessary NuGet packages in your ASP.NET Core project.
- Define a server-side Hub class that inherits from
Microsoft.AspNetCore.SignalR.Hub
. - Configure SignalR in your application's
Startup.cs
orProgram.cs
file. - Implement a client-side application (e.g., using JavaScript) to connect to the Hub and receive/send messages.
Example: Server-side Hub
Here's a simple example of a server-side Hub:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace YourApp.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
Example: Client-side JavaScript
And a corresponding JavaScript client:
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chat") // The URL of your SignalR Hub endpoint
.build();
connection.on("ReceiveMessage", (user, message) => {
const msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
const encodedMsg = user + " says " + msg;
const li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(error => {
console.error(error.message);
});
document.getElementById("sendButton").addEventListener("click", event => {
const user = document.getElementById("userInput").value;
const message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(err => {
console.error(err.toString());
});
event.preventDefault();
});
Program.cs
:
// ...
app.MapHub<ChatHub>("/chat");
// ...
Explore the rest of this documentation to learn more about advanced topics such as scaling, security, and managing groups.