gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:42:57 27 4
gpt4 key购买 nike

通过阅读其他 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com