factor_za factor_za - 5 months ago 17
jQuery Question

Send client other players score? Socket.io

I have a situation where I am not sure how to send the other client their competitors current score.

For example:

When player 1 clicks I want it to then tell player two the score of player one on the client side.

userOne = userIDs[0];
userTwo = userIDs[1];

socket.on("player one", function(data) {
console.log(data.pScore + "THIS IS WORKING");
score = data.pScore;
console.log("THIS IS PLAYER TWO" + data.pNameTwo);
if (isInArray(data.pNameTwo,allUsers)) {
console.log(users[socket.id].username);
}
socket.emit("player ones score", {p1Score: score});
});

socket.on("player two", function(data) {
console.log(data.pScore + "THIS IS WORKING");
score = data.pScore;
socket.emit("player twos score", {p2Score: score});
});


I was going to send off the score by emitting only to a specific user ID. But im not sure the best way to do so.

Answer

The best way to do so is to have an object containing all connections, which is updated every time a user connects/disconnects. I see you already have a userIDs list of their IDs, so, if your object is called userConnections, your code should be...

userOne = userIDs[0];
userTwo = userIDs[1];

socket.on("player one", function(data) {
    console.log(data.pScore + "THIS IS WORKING");
    score = data.pScore;
    console.log("THIS IS PLAYER TWO" + data.pNameTwo);
    if (isInArray(data.pNameTwo,allUsers)) {
        console.log(users[socket.id].username);
    }
    userConnections[userTwo].emit("player ones score", {p1Score: score});
});

socket.on("player two", function(data) {
    console.log(data.pScore + "THIS IS WORKING");
    score = data.pScore;
    userConnections[userOne].emit("player twos score", {p2Score: score});
}); 

UPDATE

Ok, I'll show how to initialize and manage userConnections too. It goes like this (I'm only guessing how some variables in your code are called, so I may get some names wrong).

var userConnections = {}

io.on('connection', function(socket) {
    userConnections[socket.id] = socket;

    //socket.on('player one', function(data) { ... } );
    //socket.on('player two', function(data) { ... } );

    socket.on('disconnect') {
        delete userConnections[socket.id];
    }
}