C++ 升压 ASIO : how to read/write with a timeout?

标签 c++ sockets boost-asio

通过阅读其他 Stack Overflow 条目和 boost::asio 文档,我确认没有同步 ASIO 读/写调用也提供易于使用的超时作为调用的参数。

我正在使用使用超时的 select(2) 调用转换老式 Linux 套接字应用程序,我需要或多或少地做同样的事情。

那么在 boost::asio 中最好的方法是什么?查看 asio 文档,有许多与计时器有关的各种令人困惑的示例,但我很困惑。

我希望看到一个简单易读的示例:从套接字读取,但最多等待 X 秒,之后该函数要么什么都不返回,要么返回任何内容能够在超时到期之前从套接字读取。

最佳答案

这已在 asio 邮件列表中提出,有一个 ticket也请求该功能。总而言之,如果您需要超时和可取消性,建议使用异步方法。


如果您无法转换为异步方法,您可以尝试 SO_RCVTIMEOSO_SNDTIMEO 套接字选项。可以用setsockopt设置,描述符可以用boost::asio::ip::tcp::socket::native获取方法。 man 7 socket 手册页说

SO_RCVTIMEO and SO_SNDTIMEO Specify the receiving or sending timeouts until reporting an error. The argument is a struct timeval. If an input or output function blocks for this period of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK just as if the socket was specified to be non-blocking. If the timeout is set to zero (the default) then the operation will never timeout. Timeouts only have effect for system calls that perform socket I/O (e.g., read(2), recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for select(2), poll(2), epoll_wait(2), etc.

关于C++ 升压 ASIO : how to read/write with a timeout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4553162/

相关文章:

c++ - "error C2248: ' sf::NonCopyable::NonCopyable ' : cannot access private member declared in class ' sf::NonCopyable '"

c++ - 另一个宏中的 Q_PROPERTY 宏

c++ - 什么是 "orthogonal linked list"?

linux - TCP 连接,仅限 bash

c++ - 用 gcc 编译 asio

c++ - Solaris SunStudio 12.4 标准库链接问题

c++ - 不带括号的 if 子句中多行代码块的奇怪行为

屏幕变黑后,Java Android 套接字立即被杀死

java - 基本 Netty 回显服务器 - 字符串编码器错误?

c++ - boost asio 和 shared_ptr 的扩散