如何知道Socket客户端已断开连接?
我正在Linux架构中进行编码。 我对套接字服务器和客户端有疑问。 我制作了一个示例代码,其中服务器继续接受连接并且客户端连接到服务器。 如果有人以某种方式移除了网络电缆,那么我会断开客户端连接(客户端套接字与 PC 断开连接),而在服务器端连接仍然存在,因为我无法通知客户端已断开连接,因为网络已拔出。
我怎么知道客户端已断开连接?
谢谢, 尼尔
I am doing coding in linux architecture.
I have question regarding socket server and client.
I have made one sample code in which server continue to accept the connection and client is connected to server.
if somehow someone has remove the network cable so i am disconnecting client (client socket disconnected from PC) while in server side connection is still alive because i am not able to notify that client is disconnected because network is unplugged.
How can i know that client got disconnected ?
Thanks,
Neel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在套接字上配置 keepalive 或发送应用程序级心跳消息,否则侦听端将无限期地等待数据包到达。如果控制协议,应用程序级别的心跳可能会更容易。有利的一面是,任一解决方案都有助于保持网络中跨 NAT 网关的连接处于活动状态。
请参阅此答案: 是 TCP Keepalive 是确定断开链接的唯一机制吗?
另请参阅此 Linux 文档:http://tldp.org/HOWTO/html_single/TCP-Keepalive-HOWTO/#programming
You need to either configure keepalive on the socket or send an application level heartbeat message, otherwise the listening end will wait indefinitely for packets to arrive. If you control the protocol, the application level heartbeat may be easier. As a plus side, either solution will help keep the connection alive across NAT gateways in the network.
See this answer: Is TCP Keepalive the only mechanism to determine a broken link?
Also see this Linux documentation: http://tldp.org/HOWTO/html_single/TCP-Keepalive-HOWTO/#programming
SIGPIPE 用于本地套接字,eof on read 用于每种套接字类型。
SIGPIPE for local sockets and eof on read for every socket type.