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 中设置阻塞套接字超时?


基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++,'if' 表达式中的变量声明 2021-01-01