简体   繁体   中英

Node JS server Array using Socket IO

From different Socket IO clients, I am sending an array consisting of two items back to the server. The two items are a score, and that clients socket ID and looks like this:

    [10,'_D4A1eiGJRg_ZxHRyf6A']

On the server side, on connection of the socket clients I create an object that I add the users to, based on their socket ID's: for example:

    users = {
        '_D4A1eiGJRg_ZxHRyf6A' : user {
         score : 0,
         finished : false,
         winner : false
        },
        'xnSJPYEM_aEo08T4yf5_' : user {
         score : 0,
         finished : false,
         winner : false
        },
    }

I am attempting to update this object when I send through the aforementioned array. This is the code on the server side I am using to try to achieve this:

    socket.on('finish', function(data) {
        users[data[1]]['score'] = data[0];
        users[data[1]]['finished'] = true;
    });

Instead what is happening is that ALL of the properties of the users object are being updated with the data that is being sent in the array, rather than just the one with the matching Socket ID.

Can anyone tell me what I'm doing wrong?

Thank you!

If you can do it like this and make your object as this then it will be a lot better:

users = {
    '_D4A1eiGJRg_ZxHRyf6A' : {
     score : 0,
     finished : false,
     winner : false
    },
    'xnSJPYEM_aEo08T4yf5_' : {
     score : 0,
     finished : false,
     winner : false
    },
}

Server side:

socket.on('finish', function(data) {
users[data[1]].score = data[0];
users[data[1]].finished = true;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM