如何在NodeJs中断开与tcp套接字的连接
我使用以下命令连接到 NodeJs 中的套接字服务器:
client = net.createConnection()
如何正确地从服务器断开连接?
我尝试了 client.end()
甚至 client.destroy()
但当我使用 netstat 检查连接状态时,它显示连接处于状态 FIN_WAIT2。
我怎样才能完全关闭并销毁连接?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是默认的 TCP 连接终止顺序,
通过调用
client.end()
,节点 js 将向服务器发送 FIN 数据包,服务器将用 FIN 进行响应数据包发送给客户端以接受套接字终止。根据 NodeJS 文档,
socket.end
的作用是,当收到 FIN 数据包时,客户端到服务器的连接将自动关闭,并触发
socket.on('close', .. )
并发回 ACK。因此,通过服务器和客户端都同意来终止连接,以便服务器能够在关闭连接之前发送可能需要的数据。
但是当调用
socket.destroy
时,客户端连接将在没有强制接收FIN数据包的情况下被销毁。如果可能的话,最佳实践是避免调用socket.destroy
。参考:
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,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 callingsocket.destroy
if possible.Reference:
net.createConnection()
返回一个 Socket 对象。client.destroy()
就是您想要做的。来源:http://nodejs.org/docs/latest/api/net .html#socket.destroy
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
我在GNU/Linux下安装了nodejs版本11.15.0;在此配置中断开类似 telnet 的客户端的唯一方法是调用
socket
上的其他方法根本不再存在(例如:close()
或断开连接()
);发出close
或end
事件也不起作用。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
Other methods on
socket
simply do not exist any more (eg:close()
ordisconnect()
); also emittingclose
orend
events does not work.