From cf7e0630c77b8f0e9660e3e633e10ea3db116387 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Tue, 26 Jul 2022 15:41:36 +0200 Subject: Usernames and exclude sender --- Year_3/Web/chat-socket-io/index.js | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'Year_3/Web/chat-socket-io/index.js') diff --git a/Year_3/Web/chat-socket-io/index.js b/Year_3/Web/chat-socket-io/index.js index 6224c50..b59cb72 100644 --- a/Year_3/Web/chat-socket-io/index.js +++ b/Year_3/Web/chat-socket-io/index.js @@ -13,19 +13,34 @@ app.get("/", (req, res) => { res.render("index"); }); -app.get("/chat.js", (req, res) => { - res.sendFile(__dirname + "/chat.js"); +app.use(express.static("assets")); + +app.get("*", (req, res) => { + res.render("404"); }); +const users = {}; + io.on("connection", (socket) => { - console.log("A user is connected"); + console.log("A user is connected: " + socket.id); + io.to(socket.id).emit("set user", socket.id); + users[socket.id] = socket.id; socket.on("disconnect", () => { console.log("A user is disconnected"); }); socket.on("chat message", (message) => { - io.emit("chat message", message); + socket.broadcast.emit("chat message", message); + }); + + socket.on("handle error", (msg) => { + io.emit("handle error", msg); + }); + + socket.on("set user", (username) => { + users[socket.id] = username; + io.to(socket.id).emit("set user", username); }); }); -- cgit v1.2.3-18-g5258