问题描述
有没有办法取消挂起的操作(无需断开连接)或为 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 中设置阻塞套接字超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!