I'm building a game where in order to players start a game, they should press a button, when everyone in the same room clicked the buttton the game would start.
The problem is that I managed to do this only without specifying which room sent the "I'm ready message" so I'm only counting the number of connected players regardless of where they came from:
Code to give an example:
socket.on('userReady', function(){
userReadyCounter++;
if(userReadyCounter === connectionCounter){
gameDuration = 180
io.sockets.in(socket.room).emit('startGame');
io.sockets.in(socket.room).emit('newSentence', sentences[socket.sentenceCounter]);
}
})
Connection counter part:
socket.on('joinedRoom', function(roomData){
socket.username = roomData.username;
socket.room = roomData.roomname;
socket.sentenceCounter = 0;
connectionCounter++;
socket.join(socket.room);
socket.broadcast.to(socket.room).emit('userJoined', socket.username);
});
Client:
function userReady(){
socket.emit('userReady');
}
So everytime a user send the message I'm unable to tell where they came from...
Am I doing this incorrectly?
You cannot detect on the client what room sent the data. For starters, rooms don't send messages or data. A server sends the data. The server may iterate through all connections in a room and send to them, but the message is not actually sent by the room - it's sent by the server. And, the message simply doesn't include any info in it about what room it was associated with.
So, the only way you're going to know which room a message is associated with in the client is if you either created some previous association with a room so the client just knows that messages it receives are associated with a particular room or if you send the actual room that the message is associated with inside the message itself. That would be the simplest scheme:
socket.room = roomData.roomname;
socket.join(socket.room);
socket.broadcast.to(socket.room).emit('userJoined', {
user: socket.username,
room: socket.room
});
Then, every message like this that arrives on the client informs the client exactly which room it is associated with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With