Using SignalR for Real-Time Communication in Blazor Applications

SignalR is an open-source library that allows for real-time communication between the server and the client. It gives server-side code the ability to send asynchronous updates to connected clients. Therefore, it is perfect for use in applications requiring real-time functionality, such as live notifications, chats, or collaborative tools. For Blazor, it offers two-way smooth communication between the client and the server, hence a very interactive and efficient user experience.

SignalR in Blazor Server Applications

Blazor Server applications inherently integrate SignalR to establish persistent connections between the client and server. This connection allows the server to push updates to the client in real-time whenever the server-side state changes.

Key Features in SignalR with Blazor Server

  • Persistent Connection: SignalR leverages WebSockets or other transport alternatives, including Server-Sent Events or Long Polling, to permit continuous connectivity between the client and server.
  • Real-time UI updates: Any changes on the server are automatically reflected in the client UI without refreshing the page.
  • Efficient Updates: SignalR transfers only the differences rather than the entire page, optimizing data transfer.

1. Create a SignalR Hub

A Hub is a central point for communication between clients and the server.

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

2. Configure SignalR in the Server

In your Program.cs, map the Hub endpoint:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapHub<ChatHub>("/chathub");

3. Use SignalR in a Blazor Component

Include the SignalR JavaScript library in _Host.cshtml:

<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.0/signalr.min.js"></script>

Set up a SignalR connection in your Blazor component:

@inject IJSRuntime JS

@code {
    private HubConnection? hubConnection;

    protected override async Task OnInitializedAsync()
    {
        hubConnection = new HubConnectionBuilder()
            .WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
            .Build();

        hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            // Handle incoming messages
        });

        await hubConnection.StartAsync();
    }

    private async Task SendMessage()
    {
        if (hubConnection is not null)
        {
            await hubConnection.SendAsync("SendMessage", "User", "Hello, world!");
        }
    }
}

In this example, the SendMessage method allows the client to send messages to the server, and the ReceiveMessage method handles incoming messages from the server.

SignalR in Blazor WebAssembly Applications

Unlike Blazor Server, SignalR is not built into Blazor WebAssembly by default. However, you can explicitly integrate SignalR to enable real-time features like chat or live notifications.

1. Create a SignalR Hub

The server-side setup is the same as in Blazor Server applications:

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

2. Install the SignalR Client Package

Add the SignalR client NuGet package to your Blazor WebAssembly project: Go to the “Tools” menu, select NuGet Package Manager > Package Manager Console, and then run the below commands to add database provider and Entity Framework Tools.

=> Install-Package Microsoft.AspNetCore.SignalR.Client

3. Set Up SignalR Connection

Establish the SignalR connection in your Blazor WebAssembly component:

@inject NavigationManager NavigationManager

@code {
    private HubConnection? hubConnection;

    protected override async Task OnInitializedAsync()
    {
        hubConnection = new HubConnectionBuilder()
            .WithUrl(NavigationManager.ToAbsoluteUri("/chathub"))
            .Build();

        hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            // Handle incoming messages
        });

        await hubConnection.StartAsync();
    }

    private async Task SendMessage()
    {
        if (hubConnection is not null)
        {
            await hubConnection.SendAsync("SendMessage", "User", "Hello from Blazor WebAssembly!");
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (hubConnection is not null)
        {
            await hubConnection.DisposeAsync();
        }
    }
}

In this setup, Blazor WebAssembly clients will connect to the SignalR hub, and the client-side component will handle sending and receiving messages.

Blazor Server vs. Blazor WebAssembly with SignalR
 

Feature Blazor Server Blazor WebAssembly
Default SignalR Usage Built-in and mandatory Requires explicit integration
Connection Persistent (server to client) Explicit client-to-server connection
Real-Time UI Updates Integrated for UI diffs Custom implementation needed


Summary

SignalR is a powerful library that aids in adding real-time capabilities to Blazor applications.

In Blazor Server, SignalR is effectively incorporated, facilitating continuous connections and instantaneous updates to the user interface. SignalR can be designed for the Blazor WebAssembly environment to enable functionalities like live chat, notifications, or collaborative applications.

Using WebSockets as its primary means of transport, SignalR has enabled fast and efficient exchange, making it an essential solution for modern, interactive web applications.


Similar Articles