How to set a timeout on blocking sockets in boost asio?(如何在 boost asio 中设置阻塞套接字超时?)
问题描述
有没有办法取消挂起的操作(无需断开连接)或为 boost 库函数设置超时?
Is there a way to cancel a pending operation (without disconnect) or set a timeout for the boost library functions?
即我想在 boost asio 中设置阻塞套接字超时?
I.e. I want to set a timeout on blocking socket in boost asio?
socket.read_some(boost::asio::buffer(pData, maxSize), error_);
socket.read_some(boost::asio::buffer(pData, maxSize), error_);
示例:我想从套接字中读取一些内容,但如果 10 秒过去了,我想抛出一个错误.
Example: I want to read some from the socket, but I want to throw an error if 10 seconds have passed.
推荐答案
在 Linux/BSD 下,操作系统直接支持套接字上的 I/O 操作超时.该选项可以通过 setsocktopt() 启用.我不知道 boost::asio 是否提供设置它的方法或公开套接字脚本以允许您直接设置它——后一种情况并不是真正可移植的.
Under Linux/BSD the timeout on I/O operations on sockets is directly supported by the operating system. The option can be enabled via setsocktopt(). I don't know if boost::asio provides a method for setting it or exposes the socket scriptor to allow you to directly set it -- the latter case is not really portable.
为了完整起见,这里是手册页中的描述:
For a sake of completeness here's the description from the man page:
SO_RCVTIMEO 和 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.
这篇关于如何在 boost asio 中设置阻塞套接字超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 boost asio 中设置阻塞套接字超时?
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
