ASP.NET SignalR
On this page:
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 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.
SignalR supports two models for real-time server-to-client communication:
- Persistent connections: For a direct, low-level communication channel between the client and server.
- Hubs: Higher-level abstraction that allows clients and servers to invoke methods on each other.
SignalR automatically selects the best transport method when a connection is established. This is known as negotiation. The available transports are:
- WebSockets: The preferred transport if the client and server support it.
- Server-Sent Events (SSE): A fallback for browsers that support SSE but not WebSockets.
- Long Polling: A fallback for older browsers.
Key Features
- Real-time Push: Server can push data to connected clients instantly.
- Cross-Platform: Works across various browsers and mobile devices.
- Scalability: Built to scale to large numbers of users.
- Abstracts Transports: Handles the complexity of underlying transports (WebSockets, SSE, Long Polling).
- RPC (Remote Procedure Calls): Enables clients and servers to call methods on each other.
Getting Started
To get started with SignalR, you'll typically need to:
- Install the SignalR NuGet Package: Add the appropriate SignalR package to your ASP.NET project.
- Define a Hub: Create a class that inherits from
Microsoft.AspNet.SignalR.Hub. This class will contain methods that can be called from clients and methods that can be called on clients from the server. - Configure SignalR: In your
Startup.cs(or equivalent), configure SignalR by callingapp.MapSignalR();. - Create a Client Application: Develop a client-side application (e.g., JavaScript in an HTML page) that connects to your SignalR Hub and invokes server methods or handles server-sent messages.
Example of a simple server-side Hub:
using Microsoft.AspNet.SignalR;
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addNewMessageToPage(name, message);
}
}
Real-Time Communication with SignalR
SignalR simplifies building real-time applications by abstracting away the complexities of persistent connections and transport mechanisms. The core of SignalR's real-time capabilities lies in its Hub API and its ability to manage connections efficiently.
When a client connects, SignalR negotiates the best available transport. Once a connection is established, the server can send messages to all connected clients or to specific clients.
The Hub API
The Hub class is the central point for communication in SignalR. It provides a way to send messages from the server to connected clients and to call methods on the server from clients.
Server-Side Methods (Callable by Clients)
Methods defined in the Hub that clients can call. These methods are typically marked as public.
public class MyHub : Hub
{
public void SendClientMessage(string message)
{
// Call a method on all clients
Clients.All.receiveMessage(message);
// Call a method on the sender only
// Clients.Caller.receiveMessage("You said: " + message);
// Call a method on all clients except the sender
// Clients.Others.receiveMessage(message);
}
}
Client-Side Methods (Callable by Server)
Methods defined on the client-side JavaScript that the server can invoke. These are invoked using the Clients property of the Hub.
var chat = $.connection.chat; // Assuming 'ChatHub' is mapped to 'chat'
chat.client.addNewMessageToPage = function (name, message) {
// Add message to the page
$('#discussion').append('' + name + ': ' + message + ' ');
};
Client Applications
SignalR clients can be built using JavaScript, .NET clients, and other platforms. The JavaScript client is the most common.
JavaScript Client Example
To use the JavaScript client, you need to include the SignalR JavaScript files and then start the connection.
<script src="~/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub; // Reference to the ChatHub
// Declare a function on the client that the server will call
chat.client.addNewMessageToPage = function (name, message) {
console.log('New message: ' + message);
};
// Start the connection
$.connection.hub.start().done(function () {
console.log("SignalR connection started");
// Example of calling a server method
$('#sendmessage').click(function () {
chat.server.send($('#displayname').val(), $('#message').val());
$('#message').val('').focus();
});
});
$.connection.hub.disconnected(function() {
console.log("SignalR connection disconnected");
});
});
</script>
Advanced Topics
- Connection Management: Handling connection start, stop, and errors.
- Groups: Sending messages to specific groups of clients.
- Dependency Injection: Integrating SignalR with DI containers.
- Authentication and Authorization: Securing SignalR connections.
- Backplanes: Scaling SignalR across multiple server instances (e.g., Azure SignalR Service, Redis).
- Persistent Connections API: For more low-level control.
Troubleshooting and Best Practices
- Check Transports: Understand which transport is being used and why.
- Error Handling: Implement robust error handling on both client and server.
- Keep Messages Small: Avoid sending large payloads.
- Performance Tuning: Optimize message frequency and size.
- Security: Always authenticate and authorize SignalR endpoints.