Dũng Nguyễn
Dũng Nguyễn

Reputation: 495

Socket.IO 1.0.x: Get socket by id

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?

Upvotes: 19

Views: 26253

Answers (7)

Prakash
Prakash

Reputation: 621

You can also use fetchSockets() function to fetch the connection using socketId like below.

const sockets = await io.in(theSocketId).fetchSockets();

This solution works perfectly with socket.io redis/adaptor. For more API documentation, refer here https://socket.io/docs/v4/server-api/#namespacesockets

Upvotes: 0

Sanjay Nishad
Sanjay Nishad

Reputation: 1605

Socket.io Version 4.0.0

io.sockets.sockets.get(socketId);

Upvotes: 23

isaacsan 123
isaacsan 123

Reputation: 1158

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().

Upvotes: 9

Wu Yaozu
Wu Yaozu

Reputation: 57

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.

Upvotes: 3

partikles
partikles

Reputation: 331

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

Upvotes: 7

himanshu yadav
himanshu yadav

Reputation: 1908

you can also use like:

io.to(socketid).emit();

Upvotes: 21

Sarita
Sarita

Reputation: 847

For socket.io 1.0 use:

io.sockets.connected[socketId]

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

Upvotes: 51

Related Questions