47

I connect to socket server in NodeJs using this command:

client = net.createConnection()

How can I then properly disconnect from the server?

I tried client.end() and even client.destroy()

but when I check the connection status using netstat it shows that the connection is in state FIN_WAIT2.

How can I close and destroy the connection altogether?

mgamer
  • 13,580
  • 25
  • 87
  • 145

3 Answers3

43

net.createConnection() returns a Socket object. client.destroy() is what you want to do.

Source: http://nodejs.org/docs/latest/api/net.html#socket.destroy

JP Richardson
  • 38,609
  • 36
  • 119
  • 151
  • 8
    What's the difference between end and destroy? After destroy I also see state FIN_WAIT2 in netstat. – mgamer Feb 08 '12 at 15:44
  • 5
    @mgamer ``end()`` only closes the writing stream of the socket, the remote host can keep his writing stream open and send you data – bara Feb 11 '14 at 19:34
  • 5
    Althrough docs say "Only necessary in case of errors" it seems the only method to close a connection. For myself I use something like `socket.close = function(data) { var Self = this; if (data) this.write(data, function(){ Self.destroy(); }); else this.destroy(); };` – Fr0sT Jun 10 '15 at 09:06
  • @Fr0sT your comment helped me, Thanks :-* – vahid kargar Nov 11 '17 at 14:18
40

This is the default TCP connection termination sequence,

enter image description here

By calling client.end() the node js will send the FIN packet to the server, and the server will response with a FIN packet to the client to accept the socket termination.

As of nodejs documentation what socket.end does is,

Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.

When the FIN packet is received the connection to the server from client is closed automatically and the socket.on('close', .. ) is fired and the ACK is sent back.

So the connection is terminated by agreeing both server and client so the server is able to send data that may require before closing the connection.

But when calling socket.destroy, the client connection will be destroyed without receiving the FIN packet forcefully. It is a best practice to avoid calling socket.destroy if possible.

Reference:

mhchia
  • 139
  • 1
  • 8
Janith
  • 2,730
  • 16
  • 26
6

I have nodejs version 11.15.0 installed under GNU/Linux; the only way to disconnect a telnet-like client in this configuration is to call

socket.destroy()

Other methods on socket simply do not exist any more (eg: close() or disconnect()); also emitting close or end events does not work.

bubbakk
  • 139
  • 2
  • 6