How to disconnect from tcp socket in NodeJs
Asked Answered
N

3

49

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?

Neisa answered 8/2, 2012 at 10:32 Comment(2)
Have you tried client.close()?Valvulitis
There's no client.close methodNeisa
F
44

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:

Flintlock answered 22/10, 2018 at 10:52 Comment(0)
G
42

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

Generatrix answered 8/2, 2012 at 14:51 Comment(5)
What's the difference between end and destroy? After destroy I also see state FIN_WAIT2 in netstat.Neisa
@Neisa end() only closes the writing stream of the socket, the remote host can keep his writing stream open and send you dataLilas
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(); };Monarchal
@Monarchal your comment helped me, Thanks :-*Excerpt
destroy is not a proper way to close the connection and will leave the socket in the FIN_WAIT2 state, which takes something like 2 minutes to recover from.Puparium
M
8

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.

Mcfarlane answered 22/8, 2019 at 13:1 Comment(1)
That worked for me. A simple end() would require the other end to react which in my case it doesn't...Virtually

© 2022 - 2024 — McMap. All rights reserved.