The bottom line is, I need to get an array of people who have entered the server (the name is entered before entering the site). I implemented it very badly, on the client side I create an array and on the server side the same array and they are transferred between each other, but the problem is that the array created on the client side is filled only in requests to the server, that is, in the local scope, to me you need to access it globally. Here’s the implementation:
Client part:
const userName = prompt("Enter your name:");
nameBlock.innerHTML = userName;
let arrayUser = []; // array of users
socket.emit('connect user', {
userConnect: userName, // pass the name
arrayConnect: arrayUser // we pass the array where we write the names
});
socket.on('connect user', (userName) => {
arrayUser.push(userName.arrayConnect);
const item = document.createElement('div');
item.innerHTML = `User <b><span class = "user">${userName.name}</span></b> connected to the chat!`
userConnect.append(item);
});
Server part:
let arrayUser = []; // create an array
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', {
message: msg.message,
name: msg.name
});
});
socket.on('connect user', (userName) => {
arrayUser.push(userName.userConnect);
console.log(arrayUser);
io.emit('connect user', {
name: userName.userConnect,
arrayConnect: arrayUser
});
});