feat: Änderungen werden von websocket zu client gesendet und Redux aktualisiert UI

This commit is contained in:
Ismail Ali
2025-06-07 14:25:42 +02:00
parent 17def7357c
commit a8978034d2
5 changed files with 91 additions and 52 deletions

106
server.js
View File

@@ -1,68 +1,90 @@
// server.js
const express = require("express");
const http = require("http");
const { createServer } = require("http");
const next = require("next");
const { Server } = require("socket.io");
const fs = require("fs");
const path = require("path");
const fetch = (...args) => import("node-fetch").then(({ default: fetch }) => fetch(...args));
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const PORT = 3000;
app.prepare().then(() => {
const expressApp = express();
const server = http.createServer(expressApp);
const server = createServer((req, res) => {
handle(req, res);
});
const io = new Server(server);
// Verbindung mit Clients
io.on("connection", socket => {
console.log("✅ Client verbunden via socket.io");
const { m, mode } = socket.handshake.query;
const idMap = m;
const isLiveMode = mode === "live" || mode === "prod";
socket.on("message", data => {
console.log("💬 Nachricht vom Client:", data);
});
let lastStatis = [];
socket.emit("message", { message: "Hallo vom socket.io Server" });
const fetchData = async () => {
try {
let statis;
//---------
const { m, u } = socket.handshake.query;
if (dev) {
const mockPath = path.join(process.cwd(), "mockData", "GisLinesStatus.json");
const jsonStr = fs.readFileSync(mockPath, "utf-8");
const json = JSON.parse(jsonStr);
statis = json?.Statis || [];
console.log("🧪 Mockdaten gelesen");
} else {
const fetchUrl = `http://localhost/talas5/ClientData/WebServiceMap.asmx/GisLinesStatus?idMap=${idMap}`;
const res = await fetch(fetchUrl);
const text = await res.text();
console.log(`🧩 WebSocket-Client verbunden mit Parametern: m=${m}, u=${u}`);
if (!text.startsWith("{")) {
console.error("❌ Webservice liefert kein valides JSON:", text.slice(0, 100));
return;
}
// Du kannst diese Info verwenden, um gezielt nur bestimmte Daten zu senden:
socket.join(`map-${m}-user-${u}`);
});
const json = JSON.parse(text);
statis = json?.Statis || [];
console.log("📡 Webservice-Daten empfangen");
}
// 🌍 Next.js Routing
expressApp.all("*", (req, res) => {
return handle(req, res);
});
const hasChanged =
statis.length !== lastStatis.length ||
statis.some((entry, index) => {
const prev = lastStatis[index];
return (
!prev ||
entry.Modul !== prev.Modul ||
entry.ModulName !== prev.ModulName ||
entry.Value !== prev.Value ||
entry.Level !== prev.Level
);
});
// 📁 Datei überwachen: GisLinesStatus.json (Pfad anpassen falls nötig)
const statusFilePath = path.join(__dirname, "mockData", "GisLinesStatus.json");
fs.watchFile(statusFilePath, { interval: 5000 }, async () => {
console.log("📁 Änderung erkannt: GisLinesStatus.json");
try {
const content = fs.readFileSync(statusFilePath, "utf8");
const data = JSON.parse(content);
if (Array.isArray(data.Statis)) {
io.emit("gisLinesStatusUpdated", data.Statis);
console.log("📤 Update gesendet an Clients via Socket.IO");
} else {
console.warn("⚠️ 'Statis' fehlt oder hat falsches Format");
if (hasChanged) {
lastStatis = statis;
socket.emit("gisLinesStatusUpdated", statis);
console.log("✅ Änderung erkannt und gesendet");
} else {
console.log("🔁 Keine Änderung festgestellt");
}
} catch (error) {
console.error("❌ Fehler beim Datenabruf:", error.message);
}
} catch (e) {
console.error("❌ Fehler beim Parsen von GisLinesStatus.json:", e.message);
};
if (isLiveMode) {
fetchData();
const interval = setInterval(fetchData, 5000);
socket.on("disconnect", () => {
clearInterval(interval);
console.log("❌ WebSocket getrennt");
});
}
});
// 🚀 Server starten
server.listen(port, () => {
console.log(`🚀 Server mit socket.io läuft auf http://localhost:${port}`);
server.listen(PORT, () => {
console.log(`🚀 App + Socket.io läuft auf http://localhost:${PORT}`);
});
});