Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between disconnect, close & destroy methods of socket.io

I'm working on a simple chat application using node.js & socket.io.

I'm trying to terminate the connection, for example when the user choose to leave a namespace, or something similar to logout, which doesn't exit the application or trigger a reload.

I've checked this issue @ GitHub, as well as these questions,

  • Node.js: socket.io close client connection
  • Closing a socket server side on socket.io?
  • How to close a socket.io connection

They suggest different methods such as disconnect, close etc.

As per my own experiments based on these,

Both disconnect, close methods sets the socket's connected property to false and disconnected property to true as you can see below.

enter image description here

I've also noticed a destroy method in the socket's prototype:

enter image description here

Can someone describe what exactly these methods are for, and how they are different from each other..?


Side note: It'd be great if someone can share any reference to documentation for these methods

like image 401
T J Avatar asked Nov 17 '15 20:11

T J


1 Answers

These are the typescript definitions in VSCODE:

    /**
     * Disconnects the socket manually
     * @return This Socket
     */
    close():Socket;

    /**
     * @see close()
     */
    disconnect():Socket;

Not too helpful. Looking at the Socket.IO source code for close:

/**
 * Closes the underlying connection.
 *
 * @api private
 */
Client.prototype.close = function(){
  if ('open' == this.conn.readyState) {
    debug('forcing transport close');
    this.conn.close();
    this.onclose('forced server close');
  }
};

And for disconnect:

/**
 * Disconnects from all namespaces and closes transport.
 *
 * @api private
 */
Client.prototype.disconnect = function(){
  for (var id in this.sockets) {
    if (this.sockets.hasOwnProperty(id)) {
      this.sockets[id].disconnect();
    }
  }
  this.sockets = {};
  this.close();
};

It looks like disconnect calls close after doing additional disconnecting work. I would recommend calling disconnect when you want to close, instead of just calling close.

like image 98
Harry Mumford-Turner Avatar answered Nov 05 '22 22:11

Harry Mumford-Turner