I’m building a Blazor Server application that uses SignalR to push real-time sensor data from the server to the client. The client seems to be unable to receive data, and the connection is unexpectedly closed by the server. Application is published to raspberry pi 3b (arm64 architecture). Here is a summary of the problem and the relevant code:
info: Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[6]
HttpConnection Disposed.
dbug: Microsoft.AspNetCore.SignalR.Client.HubConnection[46]
Canceling all outstanding invocations.
dbug: Microsoft.AspNetCore.SignalR.Client.HubConnection[21]
HubConnection stopped.
dbug: Microsoft.AspNetCore.SignalR.Client.HubConnection[51]
Invoking the Closed event handler.
fail: WeatherStationBlazor.Components.Pages.Weather[0]
Connection closed:
fail: Microsoft.AspNetCore.SignalR.Client.HubConnection[27]
An exception was thrown in the handler for the Closed event.
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Microsoft.AspNetCore.SignalR.Client.HubConnection'.
My Program.cs file with configuration
using Microsoft.AspNetCore.Http.Connections;
using WeatherStationBlazor.Components;
using WeatherStationBlazor.Data;
namespace WeatherStationBlazor
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddHostedService<SensorDataBackgroundService>();
builder.Services.AddSingleton<Bme280Service>();
builder.Services.AddSignalR(hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromMinutes(1);
});
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenAnyIP(5000);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.MapHub<SensorHub>("/sensorHub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
});
app.Run();
}
}
}
Client-Side Code (Blazor Component):
Here is the Blazor component that initializes the SignalR connection:
@page "/weather"
@using Microsoft.AspNetCore.SignalR.Client
@inject WeatherStationBlazor.Data.Bme280Service Bme280Service
@inject NavigationManager NavigationManager
@inject ILogger<Weather> Logger
@implements IAsyncDisposable
<h3>Real-Time Weather Data</h3>
@if (!dataLoaded)
{
<p>Loading...</p>
}
else
{
<p>Temperature: @temperature?.ToString("F2") °C</p>
<p>Humidity: @humidity?.ToString("F2") %</p>
<p>Pressure: @pressure?.ToString("F2") hPa</p>
}
@code {
private double? temperature;
private double? humidity;
private double? pressure;
private bool dataLoaded = false;
private HubConnection? hubConnection;
protected override async Task OnInitializedAsync()
{
try
{
Logger.LogInformation("Initializing Hub connection...");
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/sensorHub"))
.WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.Zero, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5) })
.ConfigureLogging(logging =>
{
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Debug);
})
.Build();
hubConnection.Closed += async (error) =>
{
Logger.LogError($"Connection closed: {error?.Message}");
await Reconnect();
};
hubConnection.On<double, double, double>("ReceiveSensorData", async (temp, hum, pres) =>
{
Logger.LogInformation($"Received data: Temperature: {temp}, Humidity: {hum}, Pressure: {pres}");
temperature = temp;
humidity = hum;
pressure = pres;
await InvokeAsync(StateHasChanged);
});
await StartHubConnectionAsync();
// Load initial data
Logger.LogInformation("Loading initial sensor data...");
var data = await Bme280Service.ReadSensorDataAsync();
temperature = data.temperature;
humidity = data.humidity;
pressure = data.pressure;
dataLoaded = true;
}
catch (Exception ex)
{
Logger.LogError($"Error initializing Hub connection: {ex.Message}");
dataLoaded = false;
}
}
private async Task StartHubConnectionAsync()
{
if (hubConnection != null && hubConnection.State == HubConnectionState.Disconnected)
{
try
{
await hubConnection.StartAsync();
Logger.LogInformation("Hub connection started successfully.");
}
catch (Exception ex)
{
Logger.LogError($"Error starting Hub connection: {ex.Message}");
await Task.Delay(5000); // Wait for 5 seconds before retrying
await StartHubConnectionAsync();
}
}
}
private async Task Reconnect()
{
Logger.LogInformation("Attempting to reconnect...");
while (hubConnection?.State == HubConnectionState.Disconnected)
{
try
{
await hubConnection.StartAsync();
Logger.LogInformation("Reconnected to Hub.");
return;
}
catch (Exception ex)
{
Logger.LogError($"Reconnection attempt failed: {ex.Message}");
await Task.Delay(2000); // Wait for 2 seconds before retrying
}
}
}
public async ValueTask DisposeAsync()
{
if (hubConnection != null)
{
var connection = hubConnection;
hubConnection = null;
try
{
await connection.StopAsync();
Logger.LogInformation("Hub connection stopped successfully.");
}
catch (Exception ex)
{
Logger.LogError($"Error stopping Hub connection: {ex.Message}");
}
finally
{
await connection.DisposeAsync();
Logger.LogInformation("Hub connection disposed.");
}
}
}
}
Setting up automatic reconnection using .WithAutomaticReconnect().
Adjusting KeepAliveInterval and ClientTimeoutInterval.
Ensuring the HubConnection is properly disposed when the component is destroyed.
Questions:
What could be causing the SignalR connection to be unexpectedly closed by the server?
How can I ensure that the client consistently receives data from the server without the connection being dropped?
Are there any specific configurations or patterns I should follow to improve the stability of the SignalR connection in a Blazor Server application?
Any help or insights would be greatly appreciated!
kamillo122 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.