websocket alle Links

This commit is contained in:
Ismail Ali
2025-06-08 10:21:19 +02:00
parent db54cc7cca
commit fbffc82e1b
8 changed files with 2018 additions and 45 deletions

129
server.js
View File

@@ -1,9 +1,9 @@
// server.js
const { createServer } = require("http");
const next = require("next");
const { Server } = require("socket.io");
const fs = require("fs");
const path = require("path");
const { saveJsonIfChanged } = require("./utils/websocket/saveJsonIfChanged");
const fs = require("fs");
const fetch = (...args) => import("node-fetch").then(({ default: fetch }) => fetch(...args));
const dev = process.env.NODE_ENV !== "production";
@@ -11,6 +11,21 @@ const app = next({ dev });
const handle = app.getRequestHandler();
const PORT = 3000;
// Hilfsfunktion zum Schreiben von JSON-Dateien bei Änderung
const writeJsonFile = (filename, data) => {
const dir = path.join(process.cwd(), "websocketDump");
if (!fs.existsSync(dir)) fs.mkdirSync(dir);
const fullPath = path.join(dir, filename);
fs.writeFileSync(fullPath, JSON.stringify(data, null, 2), "utf-8");
};
// Extrahiert relevante Datenstruktur aus Antwort
const extractData = (json, name) => {
return (
json?.Statis || json?.Points || json?.Systems || json?.Rights || json?.[name] || json || []
);
};
app.prepare().then(() => {
const server = createServer((req, res) => {
handle(req, res);
@@ -19,53 +34,83 @@ app.prepare().then(() => {
const io = new Server(server);
io.on("connection", socket => {
const { m, mode } = socket.handshake.query;
const idMap = m;
const isLiveMode = mode === "live" || mode === "prod";
const { m: idMap, u: idUser, mode } = socket.handshake.query;
const isLiveMode = mode === "live";
console.log(`🔌 WebSocket verbunden (idMap=${idMap}, idUser=${idUser}, mode=${mode})`);
let lastStatis = [];
const endpoints = [
{
name: "GisLinesStatus",
getUrl: () => `WebServiceMap.asmx/GisLinesStatus?idMap=${idMap}`,
mock: "GisLinesStatus.json",
},
{
name: "GisStationsMeasurements",
getUrl: () => `WebServiceMap.asmx/GisStationsMeasurements?idMap=${idMap}`,
mock: "GisStationsMeasurements.json",
},
{
name: "GisStationsStaticDistrict",
getUrl: () =>
`WebServiceMap.asmx/GisStationsStaticDistrict?idMap=${idMap}&idUser=${idUser}`,
mock: "GisStationsStaticDistrict.json",
},
{
name: "GisStationsStatusDistrict",
getUrl: () =>
`WebServiceMap.asmx/GisStationsStatusDistrict?idMap=${idMap}&idUser=${idUser}`,
mock: "GisStationsStatusDistrict.json",
},
{
name: "GisSystemStatic",
getUrl: () => `WebServiceMap.asmx/GisSystemStatic?idMap=${idMap}&idUser=${idUser}`,
mock: "GisSystemStatic.json",
},
];
const lastDataMap = {};
const fetchData = async () => {
try {
let statis;
for (const { name, getUrl, mock } of endpoints) {
try {
let statis;
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();
if (!text.startsWith("{")) {
console.error("❌ Webservice liefert kein valides JSON:", text.slice(0, 100));
return;
}
const json = JSON.parse(text);
statis = json?.Statis || [];
console.log("📡 Webservice-Daten empfangen");
//------------------------------------
// Änderung prüfen
const hasChanged = saveJsonIfChanged(json, lastStatis);
if (hasChanged) {
// socket.emit("gisLinesStatusUpdated", statis);
console.log("✅ Änderung erkannt und gesendet");
if (dev) {
const mockPath = path.join(process.cwd(), "mockData", mock);
const jsonStr = fs.readFileSync(mockPath, "utf-8");
const json = JSON.parse(jsonStr);
statis = extractData(json, name);
console.log(`🧪 [Mock] ${name}`);
} else {
console.log("🔁 Keine Änderung festgestellt");
const fetchUrl = `http://localhost/talas5/ClientData/${getUrl()}`;
const res = await fetch(fetchUrl);
const text = await res.text();
let json;
try {
json = JSON.parse(text);
} catch (err) {
console.error(`${name}: JSON Parsing fehlgeschlagen:`, err.message);
console.error(`🔍 Antwort war:`, text.slice(0, 300));
continue;
}
statis = extractData(json, name);
console.log(`📡 Webservice-Daten empfangen für ${name}`);
}
//------------------------------------
return;
const newDataStr = JSON.stringify(statis);
if (newDataStr !== lastDataMap[name]) {
lastDataMap[name] = newDataStr;
socket.emit(`${name}Updated`, statis);
console.log(`✅ Änderung bei ${name} erkannt → gesendet`);
writeJsonFile(`${name}.json`, statis);
} else {
console.log(`🔁 ${name}: Keine Änderung`);
}
} catch (error) {
console.error(`❌ Fehler bei ${name}:`, error.message);
}
// Nur bei Mockdaten: direkt senden
socket.emit("gisLinesStatusUpdated", statis);
} catch (error) {
console.error("❌ Fehler beim Datenabruf:", error.message);
}
};
@@ -80,6 +125,6 @@ app.prepare().then(() => {
});
server.listen(PORT, () => {
console.log(`🚀 App + Socket.io läuft auf http://localhost:${PORT}`);
console.log(`🚀 App + WebSocket läuft auf http://localhost:${PORT}`);
});
});