19

In the 0.9.x version, we can get socket by ID like this:

io.sockets.socket(socketId)

But in 1.0.x we can't. How to find a socket by id in 1.0.x?

Dũng Nguyễn
  • 485
  • 1
  • 4
  • 20

6 Answers6

51

For socket.io 1.0 use:

io.sockets.connected[socketId]

For 0.9 its io.sockets.sockets[socketId] and not io.sockets.socket[socketId]

Sarita
  • 837
  • 11
  • 19
  • 2
    For namespaced connections I could not access it via `io.sockets.connected[socketId].emit()` but it did work similarly `var nsp = io.of('/my-namespace');` then `nsp.connected[socketId].emit()`. Thanks – Luckylooke Sep 22 '16 at 05:03
  • Agreeing with @Luckylooke, I can put it into a one liner like this: `io.of('/namespace').connected[socketId].emit('message-tag', data, callback)` I think it is worth to mention that I can also pass a callback function as a bridge to request data from the connected client this way. – Aryo Jan 26 '20 at 22:03
21

Socket.io Version 4.0.0

io.sockets.sockets.get(socketId);

Sanjay Nishad
  • 1,537
  • 14
  • 26
19

you can also use like:

io.to(socketid).emit();
shkschneider
  • 17,833
  • 13
  • 59
  • 112
himanshu yadav
  • 1,818
  • 2
  • 13
  • 5
9

Version 3.0.3

// in "of", you can put '/' or whatever namespace you're using
    
io.of('/').sockets.get(socketId)

Basically, sockets is no longer a simple Object. It's a Map, so you have to use .get().

isaacsan 123
  • 1,045
  • 8
  • 11
7

Socket.io Version 2.0.3+

    let namespace = null;
    let ns = _io.of(namespace || "/");
    let socket = ns.connected[socketId] // assuming you have  id of the socket
partikles
  • 331
  • 3
  • 13
3

The most simlple way I tried is:

var socket1 = io.of("/").connected[socketId];

Then you can do

socket1.join("some room");
socket1.leave("some room");
socket1.emit();

or other things you want.

Wu Yaozu
  • 57
  • 2