Introduction to SignalR
ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have your server push content to connected clients instantly as it becomes available.
SignalR supports two server-side models:
- Hubs: A high-level abstraction that allows you to send messages to clients and handle incoming messages from clients.
- Persistent Connections: A lower-level API for clients and servers that have a persistent connection.
SignalR also handles automatically determining the best available transport mechanism for the client and server to use. This includes:
- Server-Sent Events (SSE)
- WebSockets
- Forever Frame
- Long Polling
Core Concepts
Understanding the following core concepts is crucial for effectively using SignalR:
- Hub: The core SignalR server-side component. A Hub is a pipeline that lets you call JavaScript functions from server-side .NET code, and vice versa.
- Client: The application running on the user's browser or device that connects to a SignalR Hub.
- Connection: Represents the communication channel between a client and a server.
- Transport: The underlying communication protocol used (e.g., WebSockets, Server-Sent Events, Long Polling). SignalR negotiates the best transport automatically.
Transport Mechanisms
SignalR's ability to abstract away the transport layer is one of its key strengths. It dynamically selects the most efficient and compatible transport:
- WebSockets: The preferred method when available, offering a full-duplex communication channel.
- Server-Sent Events (SSE): A standard that allows a server to push data to a client over a single HTTP connection.
- Forever Frame: Used by older browsers (like Internet Explorer) that do not support WebSockets or SSE. It creates an IFrame and continuously streams data.
- Long Polling: If none of the above are available, SignalR falls back to long polling, where the server holds a connection open until it has data to send, then the client immediately re-establishes the connection.
Hub Architecture
The Hub model simplifies real-time communication by providing a strongly-typed connection between clients and the server. A Hub class is defined on the server, and corresponding proxy classes are generated on the client.
Server-Side Hub Definition:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
Client-Side Invocation (JavaScript Example):
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().then(function () {
console.log("SignalR Connected");
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
Client-Side Programming
SignalR provides client libraries for various platforms, including JavaScript, .NET (for UWP, WPF, Xamarin, etc.), and others. The JavaScript client is most common for web applications.
Key aspects of client-side programming include:
- Establishing a connection to the Hub.
- Defining callback methods to receive messages from the server.
- Invoking server methods from the client.
- Handling connection state changes and errors.
Server-Side Programming
On the server, you configure SignalR and define your Hub classes. This involves:
- Registering SignalR services in your application's startup.
- Mapping the SignalR endpoint to your Hub.
- Implementing Hub methods that can be called by clients.
- Using the
Clients
property to broadcast messages to connected clients or send to specific clients.
Note on ASP.NET Core SignalR
While this documentation focuses on the general concepts, ASP.NET Core SignalR is the modern and recommended implementation for building real-time web applications with .NET. It offers improved performance and a streamlined development experience.
Getting Started
To start using SignalR in your ASP.NET application:
- Install the SignalR NuGet package. For ASP.NET Core, this is typically
Microsoft.AspNetCore.SignalR
. - Configure SignalR services in your
Startup.cs
file (or equivalent in newer .NET versions). - Map the SignalR endpoint using
app.MapHub<YourHubClass>("/yourHubPath");
. - Include the SignalR JavaScript library in your client-side HTML.
- Create your Hub class and implement the desired server-side logic.
- Write client-side JavaScript to connect to the Hub and handle real-time events.
Development Tip
Use browser developer tools to inspect network requests and understand how SignalR is communicating with the server. This is invaluable for debugging.