node.jsnamespacessocket.iosocket.io-1.0

Socket.IO: How do I remove a namespace


I need to be able to construct and destruct socket.io namespaces on-the-fly. It is easily to find information how to create a namespace, but I find nothing about how I remove/disconnect the namespace to release its memory.

Say I got the following code already running:

var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
  console.log('someone connected'):
});
nsp.emit('hi', 'everyone!');

How do I disconnect/remove the socket.io namespace created above?


Solution

  • The io.of method just creates an array element:

    Server.prototype.of = function(name, fn){
      if (String(name)[0] !== '/') name = '/' + name;
    
      if (!this.nsps[name]) {
        debug('initializing namespace %s', name);
        var nsp = new Namespace(this, name);
        this.nsps[name] = nsp;
      }
      if (fn) this.nsps[name].on('connect', fn);
      return this.nsps[name];
    };
    

    So I assume you could just delete it from the array in socket io. I tested it pretty quick and it seems to work. Sockets that are already connected, keep connected.

    delete io.nsps['/my-namespace'];
    

    Connecting to /my-namespace then falls back to the default namespace. I don't know if this is a good solution, but maybe you can play with this a little..