如何实现epoll超时?
我正在使用 epoll 进行网络编程。看起来工作正常。我想添加一个超时功能,这样如果客户端长时间没有发送任何内容,那么它只会断开客户端的连接。
我该怎么做?我知道我可以在 epoll_wait 中设置超时,但这不适用于单个套接字...
提前致谢...
I am working on a network programming using epoll. It seems like working fine. I would like to add a timeout function so if a client doesn't sent anything for a long period time then it will just disconnect the client.
How do I do this? I know that I can set the timeout in epoll_wait but this is not for the individual socket...
Thanks in advance...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
保留一个按剩余时间排序的套接字列表,直到超时(如果所有套接字的超时时间相同,则这相当于按最后收到消息的时间对它们进行排序)。每次调用
epoll_wait()
时,选择剩余时间最短的套接字,直到超时(它将位于列表的前面)。使用该时间作为epoll_wait()
中的超时。当
epoll_wait()
返回时,在处理任何活动套接字之后,遍历已排序的套接字列表,删除所有过期的套接字(将位于已排序列表的开头)。在
epoll_wait()
时间:Keep a list of the sockets sorted by the time remaining until they time out (if the timeout period is the same for all sockets, then this is equivalent to sorting them by the time of the last recieved message). Each time you call
epoll_wait()
, select the socket with the shortest remaining time until it times out (which will be at the front of your list). Use that time as the timeout inepoll_wait()
.When
epoll_wait()
returns, after processing any active sockets, go through the sorted list of sockets pruning all the expired ones (which will be at the start of the sorted list).At
epoll_wait()
time:您可以创建一个重复的
timerfd
并将其添加到您的 epoll 集中。它会按照您喜欢的频率唤醒您,此时您可以检查所有客户端连接并删除您认为过时的连接。
如果你的Linux太旧而无法支持timerfd,你可以尝试旧的
timer_create
。You can create a recurring
timerfd
and add it to your epoll set. It will wake you up however often you like, at which point you can check all your client connections and drop the ones you think are stale.If your Linux is too old to support timerfd, you could try the older
timer_create
.只需使用 libevent* 或类似的;这将节省实现您自己的队列和检查超时的工作。它还可以使您更轻松地使用 epoll,并且作为一个额外的好处是更加可移植(假设您想在 FreeBSD 上运行您的应用程序,它没有 epoll,但有一个概念上类似的东西,称为 kqueue)
* 其他类似的库也可用。
Just use libevent* or similar; this will save the effort of implementing your own queues and checking timeouts. It may also make your use of epoll easier, and as an added benefit be somewhat more portable (say you want to run your app on FreeBSD, which has no epoll but has something conceptually similar called kqueue)
* other similar libraries are available.