Properly getting a socket by ID
See original GitHub issueI’ve asked on IRC what the proper way is to get a socket by id from the normal namespace. Supposedly it would be io.sockets.client(id)
. Unfortunately, this method does not exist. I figured it’d be a typo, and it should be io.sockets.clients(id)
. However, the clients
method expects a room and then returns an array of all sockets in that room.
Thus, one could get a socket by id like so:
function getSocketById(id) {
var clients = io.sockets.clients(),
client = null;
clients.forEach(function(_client) {
if (_client.id === id) return (client = _client);
});
return client;
}
This is obviously rather excessive. A much more efficient way would be to access the socket by id through a library (an object where id is the key
).
From the source, another way to access a socket by id is io.sockets.socket(id);
. Unfortunately, there are 2 problems here:
- the method is flagged private
- the method creates a new socket when the given id does not exist
Thus, this method cannot be used as passing an invalid or non-existant id would trigger the creation of a dead socket.
Is there no proper way to get a client from a namespace by id at the moment?
Issue Analytics
- State:
- Created 12 years ago
- Comments:18 (2 by maintainers)
Top GitHub Comments
@romelperez But whole this comments thread is based on a comment of @tommedema stating that using
forEach
in your case some underscore.js function, is excessive. Not an array but a hash would be more efficient or convenient.io.sockets.sockets is an array of sockets, so you can
using underscore or
more general. Have in mind that io.sockets is the “/” namespace. For specific namespace: io.of(‘/ns’).sockets.