Skip to content

Properly getting a socket by ID #503

Closed
@tommedema

Description

@tommedema

I'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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions