5

Is there a way to get a sockets namespace? I've tried various things but cannot get it to work. Given a socket object I would like to be able to know what namespace it belongs to. Thank you very much.

for example

nsp = io.of('/' + venue_code).on('connection', function(socket) {
    socket.namespace = nsp
    if (typeof servers[nsp.name] == 'undefined') {
        servers[nsp.name] = socket.id
        winston.debug("Server " + socket.id + " connected to " + nsp.name)
        socket.room = "servers"
        socket.join(socket.room)
    } else {
        socket.room = "clients"
        socket.join(socket.room)
        winston.debug("Client " + socket.id + " connected to " + nsp.name)
    }
patrick_corrigan
  • 809
  • 11
  • 24

1 Answers1

10

It is just socket.nsp, which gives the entire Namespace object. Use socket.nsp.name to get the actual name.

nsp = io.of('/' + venue_code).on('connection', function(socket) {
    winston.debug(socket.nsp)
}

Note that if you attach this same handler to the root namespace, you'll get the root namespace -- those middlewares are run before the correct namespace is attached.

Nic
  • 6,211
  • 10
  • 46
  • 69
patrick_corrigan
  • 809
  • 11
  • 24
  • 2
    This doesn't work in `io.on('connection', ...)` -- it thinks I'm connecting to `/`, not `/actual-nsp`. – Nic Jun 02 '18 at 05:00