0

Is it possible to get the socket.id from the client thats emits something?

Like:

Clientside:

socket.emit("lol", "data")

Server side:

socket.on("lol", function(data) {
        // get the socket.id from the client who sended this!!
});

So, I`m making a Tic Tac Toe game in multiplayer. I'm using rooms. In each room there are 2 players. But I need to detect in which room the player is that clicked a field.

I can also explain it like this:

Server side:

 player1.on("click", function(data) {
                console.log(data + " in room" + playRoom);   
 });

But this is not working.

DazDylz
  • 1,028
  • 3
  • 13
  • 39

1 Answers1

0

I'm going to use answer format, but this may be only directionally correct :) If you want to send data to a room, the client has to specify what room to send to. For example:

socket.broadcast.to('room').emit('event_name', data);

To join a room:

socket.join('room');

This SO answer has a nice way of showing how a single socket could emit to multiple rooms (but I don't see the emitter actually subscribed to the room): https://stackoverflow.com/a/16475058/1861459

To your actual question of the client's ID - I might debug through socket.rooms to see if you can divine what specific ID each room's subscription has: https://github.com/Automattic/socket.io/wiki/Rooms#rooms-a-client-has-joined however, I don't see how this helps you - if you join a room and broadcast to a room the library is taking care of the namespacing for you.

Community
  • 1
  • 1
pherris
  • 17,195
  • 8
  • 42
  • 58
  • Also checkout custom namespaces here: http://socket.io/docs/rooms-and-namespaces/ where the client could do `var socket = io('/my-namespace');` – pherris Dec 04 '14 at 20:15