I have a simple socket.io application where I can track when users connect and disconnect from my site. However, the issue is that only the first user who connects can see all current connected users, while subsequent users can only see users who join after them. I want every user who connects to be able to see the entire list of currently connected users.
Server.js
var io = require("socket.io")(http);
var users = [];
io.on("connection", function (socket) {
console.log("User connected", socket.id);
// Need help with creating a loop to display connected users
socket.on("user_connected", function (username) {
users[username] = socket.id;
console.log(users);
if (username !== 'null'){
io.emit("user_connected", username);
}
});
socket.on("send_message", function (data) {
io.emit("new_message", data);
});
socket.on("user_left", function (datan) {
io.emit("user_remove", datan);
console.log("user left", datan);
});
});
site.html
window.onbeforeunload = function () {
io.emit("user_left", name);
};
var name = <?php echo json_encode($_SESSION['displayname']); ?>;
var image = <?php echo json_encode($_SESSION['userpic']);?>;
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes();
io.emit("user_connected", name);
sender = name;
io.on("user_connected", function (username) {
var html = "";
html += "<li data-username='" + username + "'>" + username + "</li>";
document.getElementById("users").innerHTML += html;
});
I tried referring to this question for guidance, but I couldn't quite grasp how 'my_room' relates to my solution. Apologies for the confusing question, I'm just feeling a bit lost in this code.