Я создаю серверное приложение Blazor, которое использует SignalR для передачи данных датчиков в реальном времени с сервера клиенту. Похоже, клиент не может получить данные, а соединение неожиданно закрывается сервером. Приложение опубликовано для Raspberry Pi 3b (архитектура Arm64). Вот краткое описание проблемы и соответствующий код:
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'.
Мой файл Program.cs с конфигурацией
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();
builder.Services.AddSingleton();
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()
.AddInteractiveServerRenderMode();
app.MapHub("/sensorHub", options =>
{
options.Transports =
HttpTransportType.WebSockets |
HttpTransportType.LongPolling;
});
app.Run();
}
}
}
Код на стороне клиента (компонент Blazor):
Вот компонент Blazor, который инициализирует соединение SignalR:
@page "/weather"
@using Microsoft.AspNetCore.SignalR.Client
@inject WeatherStationBlazor.Data.Bme280Service Bme280Service
@inject NavigationManager NavigationManager
@inject ILogger Logger
@implements IAsyncDisposable
Real-Time Weather Data
@if (!dataLoaded)
{
Loading...
}
else
{
Temperature: @temperature?.ToString("F2") °C
Humidity: @humidity?.ToString("F2") %
Pressure: @pressure?.ToString("F2") hPa
}
@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("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.
Вопросы:
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!
Подробнее здесь: https://stackoverflow.com/questions/785 ... pplication
Соединение SignalR неожиданно закрывается в серверном приложении Blazor ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Проблема с распространением XtraReport с помощью докера в серверном приложении blazor
Anonymous » » в форуме C# - 0 Ответы
- 33 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Ошибка приведения объекта типа в серверном приложении Blazor в сеансе .NET 6.
Anonymous » » в форуме C# - 0 Ответы
- 10 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Ошибка приведения объекта типа в серверном приложении Blazor в сеансе .NET 6.
Anonymous » » в форуме C# - 0 Ответы
- 17 Просмотры
-
Последнее сообщение Anonymous
-