const http = require("http");
const fs = require("fs");
const path = require("path");
const players = {};
const streams = {};
let nextId = 1;
function broadcast() {
const data = "data: " + JSON.stringify(players) + "\n\n";
for (const id in streams) streams[id].write(data);
}
const server = http.createServer((req, res) => {
if (req.url === "/events") {
if (Object.keys(streams).length >= 2) { res.writeHead(403); return res.end("Partie pleine"); }
const id = String(nextId++);
res.writeHead(200, {"Content-Type":"text/event-stream","Cache-Control":"no-cache","Connection":"keep-alive"});
res.write("event: hello\ndata: " + id + "\n\n");
streams[id] = res;
players[id] = {x:0,z:0,yaw:0};
broadcast();
req.on("close", () => { delete streams[id]; delete players[id]; broadcast(); });
return;
}
if (req.method === "POST" && req.url.startsWith("/move/")) {
const id = req.url.split("/")[2];
let body = "";
req.on("data", c => { body += c; if (body.length > 500) req.destroy(); });
req.on("end", () => {
try {
const m = JSON.parse(body);
if (players[id]) { players[id] = {x:+m.x||0, z:+m.z||0, yaw:+m.yaw||0}; broadcast(); }
} catch (e) {}
res.end("ok");
});
return;
}
res.writeHead(200, {"Content-Type":"text/html; charset=utf-8"});
res.end(fs.readFileSync(path.join(__dirname, "index.html")));
});
server.listen(process.env.PORT || 3000, "0.0.0.0", () => console.log("Serveur prĂȘt"));