Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it need to socket.leave() a room on disconnect in Nodejs

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?
});
like image 302
Pars Avatar asked Feb 13 '17 07:02

Pars


2 Answers

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
};
like image 73
Shaharyar Avatar answered Sep 19 '22 12:09

Shaharyar


No you dont need to manually call socket.leave() when disconnect event fires. see http://socket.io/docs/rooms-and-namespaces/ for more details

like image 24
Ahmed Hassan Avatar answered Sep 19 '22 12:09

Ahmed Hassan