1

I am trying to access a socket by its id. I have seen this and this stackoverflow posts. However,

io.sockets.connected[socket.id]

returns undefined.

This also doesn't work :

io.to(socket.id).emit("myMessage");

Socket is connected to a namespace (socket.id returns /playNS#1HhBtUM-6O_YsRwmAAAF) and socket.io version is 1.4.5. What am I doing wrong?

Community
  • 1
  • 1
StackExploded
  • 539
  • 7
  • 17
  • That should work fine -- I have similar code in a github project and the only thing I do is track socketID and sessionID in an object – Sterling Archer Apr 04 '16 at 16:14

1 Answers1

4

If a socket is connected to a namespace, the first part of socket.id contains that namespace (e.g. /playNS#1HhBtUM-6O_YsRwmAAAF) , but io.sockets.connected property for that socket would be /#1HhBtUM-6O_YsRwmAAAF

In order to properly retrieve the socket I used io.of('/namespace').connected[socket.id].

Similarly, io.of("/namespace").to(socket.id).emit("myMessage"); to send a message

StackExploded
  • 539
  • 7
  • 17