diff --git a/index.js b/index.js index 2645f16..119f9df 100644 --- a/index.js +++ b/index.js @@ -20,18 +20,27 @@ const io = socketio(socketHTTPSServer, { secure: true }); -usersConnected = 0 +usersConnected = 0; +lastUsername = 0; io.on("connection", (client) => { usersConnected++; + io.sockets.emit("update-count", {value: usersConnected}); client.on("disconnect", () => { usersConnected--; io.sockets.emit("update-count", {value: usersConnected}); }); - io.sockets.emit("update-count", {value: usersConnected}); + client.on("message", (data) => { + io.sockets.emit("new-message", {author: client.usernameDenis, message: data.message}); + }); + + lastUsername++; + client.usernameDenis = "DenisFan" + lastUsername; + client.emit("username", {username: "DenisFan" + lastUsername}); + }); diff --git a/src/script.js b/src/script.js index 18db3bb..b3f38ae 100644 --- a/src/script.js +++ b/src/script.js @@ -1,3 +1,6 @@ +var socket; +var username = ""; + function addMessage(author, message) { var li = document.createElement("li"); li.innerHTML = "" + author + ": "; @@ -6,6 +9,7 @@ function addMessage(author, message) { } function sendMessage() { + socket.emit("message", {message: document.getElementById("message-input").value}); document.getElementById("message-input").value = ""; } @@ -13,12 +17,21 @@ function sendMessage() { document.addEventListener("DOMContentLoaded", () => { try { - var socket = io("https://danby.aniere.fr:3000"); + socket = io("https://danby.aniere.fr:3000"); socket.on("update-count", (data) => { document.getElementById("value").innerText = data.value; }); + socket.on("username", (data) => { + username = data.username; + }); + + socket.on("new-message", (data) => { + addMessage(data.author, data.message); + }); + + } catch(error) { document.getElementById("value").innerText = "Serveur injoingnable !"; }