C++ Boost ASIO:如何超时读/写?
通过阅读其他 Stack Overflow 条目和 boost::asio
文档,我已经确认没有同步 ASIO 读/写调用也提供了易于使用的超时作为参数称呼。
我正在使用使用超时的 select(2) 调用来转换老式 Linux 套接字应用程序,并且我需要做或多或少相同的事情。
那么在 boost::asio 中执行此操作的最佳方法是什么?查看 asio 文档,有许多与计时器有关的各种令人困惑的示例,但我很困惑。
我很想看到一个简单易读的示例:从套接字读取,但最多等待 X 秒,之后函数要么不返回任何内容,要么返回它能够读取的任何内容在超时到期之前从套接字中获取。
From reading other Stack Overflow entries and the boost::asio
documentation, I've confirmed that there is no synchronous ASIO read/write calls that also provide an easy-to-use timeout as a parameter to the call.
I'm in the middle of converting an old-school Linux socket application with select(2) calls that employs timeouts, and I need to do more-or-less the same.
So what is the best way to do this in boost::asio
? Looking at the asio documentation, there are many confusing examples of various things to do with timers, but I'm quite confused.
I'd love to see a simple-to-read example of this: Read from a socket, but wait for a maximum of X seconds after which the function either returns with nothing, or returns with whatever it was able to read from the socket before the timeout expired.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这已在 asio 邮件列表中提出,有一个请求该功能的 ticket以及。总而言之,如果您需要超时和可取消性,建议使用异步方法。
如果无法转换为异步方法,您可以尝试
SO_RCVTIMEO
和SO_SNDTIMEO
套接字选项。它们可以使用setsockopt
设置,描述符可以使用 boost::asio::ip::tcp::socket::native 方法。man 7 socket
手册页说This has been brought up on the asio mailing lists, there's a ticket requesting the feature as well. To summarize, it is suggested to use asynchronous methods if you desire timeouts and cancellability.
If you cannot convert to asynchronous methods, you might try the
SO_RCVTIMEO
andSO_SNDTIMEO
socket options. They can be set withsetsockopt
, the descriptor can be obtained with the boost::asio::ip::tcp::socket::native method. Theman 7 socket
man page says我使用了一些 asio 文档 来生成此内容:
用法:
我调试了它,它似乎做了它应该做的事情。
I used some asio docs to produce this:
Usage:
I debugged it, and it appears to do what it is supposed to.