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:
2025-02-06 22:21:53 +01:00
parent 892b2183e0
commit be2599218d
12 changed files with 202 additions and 15 deletions

View File

@@ -2,26 +2,53 @@ import React, { useEffect, useState } from 'react';
import logo from './logo.svg';
import './App.css';
import { Client, WeatherForecast } from './ApiCient';
import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';
function App() {
const [forecast, setForecast] = useState<WeatherForecast[] | undefined>([]);
const [connection, setConnection] = useState<HubConnection | null>(null);
useEffect(() => {
const client = new Client();
const newConnection = new HubConnectionBuilder()
.withUrl('http://localhost:5175/WeatherUpdateHub') // adjust the URL/port as needed
.withAutomaticReconnect()
.build();
const fetchForecast = async () => {
const forecast = await client.getWeatherForecast();
setForecast(forecast);
};
fetchForecast();
const intervalId = setInterval(fetchForecast, 1000);
return () => clearInterval(intervalId);
setConnection(newConnection);
}, []);
useEffect(() => {
if (connection) {
connection
.start()
.then(() => {
console.log('Connected to SignalR hub!');
connection.on('ReceiveMessage', (user, message) => {
console.log('Received message:', user, message);
});
})
.catch(error => console.error('SignalR Connection Error: ', error));
}
}, [connection]);
// useEffect(() => {
// const client = new Client();
// const fetchForecast = async () => {
// const forecast = await client.getWeatherForecast();
// setForecast(forecast);
// };
// fetchForecast();
// const intervalId = setInterval(fetchForecast, 1000);
// return () => clearInterval(intervalId);
// }, []);
return (
<div className="App">