SignalR is a real-time communication framework that enables bi-directional communication between servers and clients. It provides support for various types of communication, such as WebSocket, Server-Sent Events (SSE), and long polling.
With SignalR, you can easily push real-time updates, notifications, and messages from the server to the connected clients, eliminating the need for clients to constantly send requests to the server for updates. This greatly reduces the latency and improves the overall performance of your application.
To use SignalR in your application, you need to follow these steps:
1. Install the SignalR package:
“`
dotnet add package Microsoft.AspNetCore.SignalR
“`
2. Create a SignalR hub class that inherits from the `Hub` class:
“`csharp
public class MyHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync(“ReceiveMessage”, user, message);
}
}
“`
3. Configure SignalR in the `Startup` class:
“`csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
“`
“`csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// …
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub
});
}
“`
4. Connect to the SignalR hub from the client-side:
“`javascript
const connection = new signalR.HubConnectionBuilder()
.withUrl(“/myhub”)
.build();
connection.start()
.then(() => {
console.log(“Connection established.”);
})
.catch(err => console.error(err));
connection.on(“ReceiveMessage”, (user, message) => {
console.log(`${user}: ${message}`);
});
“`
5. Send messages to the hub from the client-side:
“`javascript
const user = “John”;
const message = “Hello, world!”;
connection.invoke(“SendMessage”, user, message)
.catch(err => console.error(err));
“`
With this setup, whenever a client sends a message to the hub using the `SendMessage` method, the hub will send the message to all connected clients using the `ReceiveMessage` method. The clients can then handle the received messages and update their UI accordingly.
SignalR takes care of all the underlying transport protocols and fallback mechanisms, allowing you to focus on building real-time features without worrying about the low-level details. It also provides features like group communication, authentication, and authorization, making it a powerful tool for building real-time applications.