Socket.IO: How do I remove a namespace

淺唱寂寞╮ 提交于 2019-12-05 05:49:08

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..

Actually by just deleting the namespace from the server nsps array you will not free any memory and sockets will still remain connected since there are still pointers to the Namespace in memory, so it will not be Garbage Collected... If what you want is to completely empty the resource you should

  1. disconnect all the sockets from the specific namespece
  2. delete all event listeners since it is an EventEmitter extented class
  3. remove it from the nsps array in the server

For example

const MyNamespace = io.of('/my-namespace'); // Get Namespace
const connectedNameSpaceSockets = Object.keys(MyNamespace.connected); // Get Object with Connected SocketIds as properties
connectedNameSpaceSockets.forEach(socketId => {
    MyNamespace.connected[socketId].disconnect(); // Disconnect Each socket
});
MyNamespace.removeAllListeners(); // Remove all Listeners for the event emitter
delete io.nsps['/my-namespace']; // Remove from the server namespaces
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!