如何检查客户端连接是否仍然有效
我正在使用 epoll 进行网络编程。我有一个连接列表,并将每个客户端都放在列表中。如果用户正常断开连接,我可以通过读取 0 来检测用户断开连接。但是,如果用户以某种方式意外断开连接,那么在尝试向用户发送数据之前,它无法知道这一点。
我不认为 epoll 提供了一个很好的方法来处理这个问题......所以我认为我应该自己处理这个问题。如果你们能为我提供与此问题相关的示例或参考资料,我将不胜感激。
I am working on a network programming using epoll. I have a connection list and put every client in the list. I can detect user disconnection by reading 0 if the user disconnected normally. However, if the user somehow got disconnected unexpectedly then there is no way it knows about this until it tries send data to the user.
I don't think epoll provides a nice way to handle this..so I think I should handle this on my own. I will be very appreciated if you guys can provide me anything like examples or references related to this problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果对方断开连接,epoll_wait 将为套接字返回 EPOLLHUP 或 EPOLLERR。 EPOLLHUP 和 EPOLLERR 是自动设置的,但您也可以设置较新的 EPOLLRDHUP,它显式报告对等关闭。
此外,如果您使用带有 MSG_NOSIGNAL 标志的发送,它将在关闭的连接上设置 EPIPE。
比收到信号好得多。
epoll_wait will return a EPOLLHUP or EPOLLERR for the socket if the other side disconnects. EPOLLHUP and EPOLLERR are set automatically but you can also set the newer EPOLLRDHUP which explicitly reports peer shutdown.
Also if you use send with the flag MSG_NOSIGNAL it will set EPIPE on closed connections.
Much nicer than getting a signal.
TCP Keepalive 怎么样: http://tldp.org/HOWTO/TCP-Keepalive- HOWTO/overview.html。请参阅“检查死亡对等点”。同一站点上的后续部分有示例代码: http://tldp.org/ HOWTO/TCP-Keepalive-HOWTO/programming.html。
How about TCP Keepalives: http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html. See "Checking for dead peers". A later section on the same site has example code: http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/programming.html.