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:
@@ -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">
|
||||
|
||||
Reference in New Issue
Block a user