Home>

The bottom line is this, 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 side:

const userName= prompt ("Enter your nickname:");
nameBlock.innerHTML= userName;
let arrayUser= []; //array of users
socket.emit ('connect user', {
    userConnect: userName, //pass the name
    arrayConnect: arrayUser //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 chat! `
    userConnect.append (item);
})

Server side:

let arrayUser= []; //also 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
        });
    });

Why do you need a client-side array? You can change it. It is not safe. It is much easier to store this array on the server side and as soon as the client comes in, an event is sent to the server (+ your name). The server adds the name to the array and sends new information to all clients. Having received this information, users update their data.

KordDEM2022-01-12 11:16:48

I also wanted to do that, store the array only on the server, but how can I then transfer this to socket.emit (we send a request to the server), as the second field of the object I have an array of objects, I can just send a dummy there, and then it will be filled?

Марьяна2022-01-12 11:21:39