socket.io und mock Data

This commit is contained in:
Ismail Ali
2025-06-07 09:12:58 +02:00
parent a55b5b0189
commit 17def7357c
4 changed files with 53 additions and 12 deletions

View File

@@ -3,6 +3,8 @@ const express = require("express");
const http = require("http");
const next = require("next");
const { Server } = require("socket.io");
const fs = require("fs");
const path = require("path");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
@@ -14,7 +16,7 @@ app.prepare().then(() => {
const server = http.createServer(expressApp);
const io = new Server(server);
// WebSocket-Logik
// Verbindung mit Clients
io.on("connection", socket => {
console.log("✅ Client verbunden via socket.io");
@@ -23,13 +25,43 @@ app.prepare().then(() => {
});
socket.emit("message", { message: "Hallo vom socket.io Server" });
//---------
const { m, u } = socket.handshake.query;
console.log(`🧩 WebSocket-Client verbunden mit Parametern: m=${m}, u=${u}`);
// Du kannst diese Info verwenden, um gezielt nur bestimmte Daten zu senden:
socket.join(`map-${m}-user-${u}`);
});
// Next.js Routen
// 🌍 Next.js Routing
expressApp.all("*", (req, res) => {
return handle(req, res);
});
// 📁 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");
}
} catch (e) {
console.error("❌ Fehler beim Parsen von GisLinesStatus.json:", e.message);
}
});
// 🚀 Server starten
server.listen(port, () => {
console.log(`🚀 Server mit socket.io läuft auf http://localhost:${port}`);
});