Add SignalR integration for real-time weather updates
Implemented SignalR to enable real-time communication between the server and connected clients. Added a new hub (`WeatherUpdateHub`), a background service (`SignalRSendService`), and modified both the API backend and React frontend for seamless message broadcasting and handling.
This commit is contained in:
31
Api/SignalR/SignalRSendService.cs
Normal file
31
Api/SignalR/SignalRSendService.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
|
||||
namespace Api.SignalR
|
||||
{
|
||||
public class SignalRSendService(IHubContext<WeatherUpdateHub> hubContext, ILogger<SignalRSendService> logger) : BackgroundService
|
||||
{
|
||||
|
||||
#region Override ExecuteAsync
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
// For example, wait 10 seconds between messages.
|
||||
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
|
||||
|
||||
// Log or do any work here.
|
||||
logger.LogInformation("Background service sending message at: {Time}", DateTime.Now);
|
||||
|
||||
// Send a message to all connected clients.
|
||||
await hubContext.Clients.All.SendAsync(
|
||||
"ReceiveMessage", // This is the client method name.
|
||||
"Background Service", // Example sender.
|
||||
"Hello from the background task!", // The message.
|
||||
stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user