如何检查客户端连接是否仍然存在 [英] How do I check client connection is still alive

查看:82
本文介绍了如何检查客户端连接是否仍然存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 epoll 进行网络编程.我有一个连接列表并将每个客户端都放在列表中.如果用户正常断开连接,我可以通过读取 0 来检测用户断开连接.但是,如果用户以某种方式意外断开连接,那么在尝试向用户发送数据之前,它无法知道这一点.

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.

我不认为 epoll 提供了一个很好的方法来处理这个..所以我认为我应该自己处理这个.如果你们能提供任何与此问题相关的示例或参考资料,我将不胜感激.

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.

推荐答案

epoll_wait 如果另一端断开连接,将为套接字返回 EPOLLHUP 或 EPOLLERR.EPOLLHUP 和 EPOLLERR 是自动设置的,但您也可以设置较新的 EPOLLRDHUP,它明确报告对等关闭.

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.

此外,如果您使用带有标志 MSG_NOSIGNAL 的发送,它将在关闭的连接上设置 EPIPE.

Also if you use send with the flag MSG_NOSIGNAL it will set EPIPE on closed connections.

int resp = send (sock, buf, buflen, MSG_NOSIGNAL);

int resp = send ( sock, buf, buflen, MSG_NOSIGNAL );

if ( resp == -1 && errno == EPIPE ) {/* 另一边消失了 */}

if ( resp == -1 && errno == EPIPE ) { /* other side gone away */ }

比接收信号要好得多.

这篇关于如何检查客户端连接是否仍然存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆