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,
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.
I've also noticed a destroy
method in the socket's prototype:
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With