node.jssocket.io

Does it need to socket.leave() a room on disconnect in Socket.io?


In socket.io, Do I need to manually call socket.leave() when disconnect fires?
or NodeJs Socket.io itself handles it?

socket.on("disconnect" function() {
   this.leave("room"); // is this necessary?
});

Solution

  • No, all rooms are already left before emitting this event.

    Code from socket.io:

    Socket.prototype.onclose = function(reason){
      if (!this.connected) return this;
      debug('closing socket - reason %s', reason);
      this.emit('disconnecting', reason);
      this.leaveAll();   //leaving all rooms
      this.nsp.remove(this);
      this.client.remove(this);
      this.connected = false;
      this.disconnected = true;
      delete this.nsp.connected[this.id];
      this.emit('disconnect', reason);   //emitting event
    };