add backend chat

This commit is contained in:
Quentin ANIERE 2022-04-12 10:43:11 +02:00
parent 45cdd713bd
commit 932ddcd102
2 changed files with 25 additions and 3 deletions

View File

@ -20,18 +20,27 @@ const io = socketio(socketHTTPSServer, {
secure: true secure: true
}); });
usersConnected = 0 usersConnected = 0;
lastUsername = 0;
io.on("connection", (client) => { io.on("connection", (client) => {
usersConnected++; usersConnected++;
io.sockets.emit("update-count", {value: usersConnected});
client.on("disconnect", () => { client.on("disconnect", () => {
usersConnected--; usersConnected--;
io.sockets.emit("update-count", {value: 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});
}); });

View File

@ -1,3 +1,6 @@
var socket;
var username = "";
function addMessage(author, message) { function addMessage(author, message) {
var li = document.createElement("li"); var li = document.createElement("li");
li.innerHTML = "<b>" + author + ": </b>"; li.innerHTML = "<b>" + author + ": </b>";
@ -6,6 +9,7 @@ function addMessage(author, message) {
} }
function sendMessage() { function sendMessage() {
socket.emit("message", {message: document.getElementById("message-input").value});
document.getElementById("message-input").value = ""; document.getElementById("message-input").value = "";
} }
@ -13,12 +17,21 @@ function sendMessage() {
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
try { try {
var socket = io("https://danby.aniere.fr:3000"); socket = io("https://danby.aniere.fr:3000");
socket.on("update-count", (data) => { socket.on("update-count", (data) => {
document.getElementById("value").innerText = data.value; 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) { } catch(error) {
document.getElementById("value").innerText = "Serveur injoingnable !"; document.getElementById("value").innerText = "Serveur injoingnable !";
} }