How to disconnect from tcp socket in NodeJs

a 夏天 提交于 2020-01-11 17:23:13

问题


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?


回答1:


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




回答2:


This is the default TCP connection termination sequence,

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 and is a best practice to avoid if possible.

Reference:

  • NodeJS net documentation
  • TCP Connection Termination



回答3:


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.




回答4:


What you want is client.close(), the client keeps then alive for future connections. If you dont want to use the connection anymore in the near future you can destroy() it. I must say in my humble opinion the semantics are not that consistent in net.Socket . You connect() a Socket and the opposite is close() . open() a Socket would be more appropiate. client-end() sends a fin packet to server



来源:https://stackoverflow.com/questions/9191587/how-to-disconnect-from-tcp-socket-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!