socket.io-redis-adapter: io.of('/').connected[socketId] does not always return socket object

Before implementing socket.io-redis I used the following to get the socket object:

var socket = io.sockets.connected[socketId];

Now that I’ve implemented socket.io-redis I guess the command to replace it is:

var socket = io.of('/).connected[socketId];

However, it returns undefined in many, many cases where the socket actually exists.

I need to know how to get a socket’s object by its id but without using any callback function since in my initial implementation I used as a return value as showed above and it is being currently used in many parts of the app.

UPDATE Jun 20th

I’ve also unsucessfully tried with io.of('/').adapter.nsp.connected[socket_id];. It replies with the right socket object for just some cores, not for all of them, returning undefined most of the time.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 16 (3 by maintainers)

Commits related to this issue

Most upvoted comments

@darrachequesne yes i ditched socket.io-request and implemented own way to fetch data from a socket connected to another server everything else is working as expected , Thanks @darrachequesne @jaymehtasa

@Manjukb I will not able to help further as I have never worked with socket.io-request.

FYI, the code I have provided works 100% because it’s in production and being used by 3M people, we have tons of NodeJS servers running in parallel in cluster mode.

We have never faced any issue, you may change your architecture the way I have suggested, it must work.

@joanmooreban @jaymehtasa if you used multiple nodes architecture, the connected socket object was “only” existed in connected node scope. You may get “undefined” if your wanted socket is not in local instance scope.

therefore, if you really want some “attributes” of socket object you can use…

solutions: customHook, customRequest,

You can use customRequest to communicate with other node instance and retrieve some attributes of “socket object” by specific socketId.

hook the function on your application, and use customRequest to get you wanted.

The socket is not shared accross all nodes:

// node1
io.on('connect', (socket) => {
  // io.sockets.connected[socket.id] === socket
});

// node2
// io.sockets.connected[socket.id] == undefined