From 1b52ac9f7be28e400bffb3f93740a4dbd8db8502 Mon Sep 17 00:00:00 2001 From: Arne van Iterson Date: Wed, 22 Apr 2020 20:17:09 +0200 Subject: [PATCH] [wip] Added basic client - server communication Encountering issues with socket id's in players array --- src/index.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index 06d33a7..cd536f2 100644 --- a/src/index.js +++ b/src/index.js @@ -13,9 +13,53 @@ app.get("/index.css", (req, res) => { res.sendFile(path.join(__dirname + "/../css/index.css")); }); -// eslint-disable-next-line no-unused-vars +var players = []; + +// Handle Connection io.on("connection", (socket) => { - console.log("A user connected"); + // Handle disconnection + socket.on("disconnect", () => { + delete players[String(socket.id)]; + console.warn(players); + console.log(`User ${socket.id} disconnected!`); + }); + + // Request identification + socket.emit("identify"); + + // Wait for identification + socket.on("identification", (data) => { + var room; + switch (data.gamemode) { + case 2: + room = "2_01"; + break; + case 4: + room = "4_01"; + break; + } + + socket.join(room); + + players[String(socket.id)] = { + username: data.name, + room: room + }; + console.warn(players); + + io.in(room).emit("roomUpdate", players); + + console.log(`User ${socket.id} connected to room ${room}`); + }); + + socket.on("update", (data) => { + if (players[String(socket.id)]) { + socket.to(players[String(socket.id)].room).emit("update", { + uuid: String(socket.id), + controls: data + }); + } + }); }); http.listen(3000, () => {