有没有办法取消挂起操作(没有断开连接)或设置升压库函数的超时?
即我想在boost asio中阻止套接字设置超时?
socket.read_some(boost :: asio :: buffer(pData,maxSize),error_);
示例:我想从套接字中读取一些内容,但是如果已经过了10秒,我想抛出一个错误.
我有一个使用Boost.Asio进行TCP和UDP套接字通信的应用程序.我知道"Asio"中的"A"代表异步,因此库倾向于鼓励您尽可能使用异步I/O. 我有一些情况下,优选同步套接字读取.但是,与此同时,我想在所述接收调用上设置超时,因此不可能无限期地进行读取阻塞.
这似乎是Boost.Asio用户中一个非常常见的问题,以下是关于该主题的以下Stack Overflow问题:
甚至可能还有更多.文档中甚至有关于如何使用超时实现同步操作的示例.他们归结为将同步操作转换为异步操作,然后与a并行启动asio::deadline_timer.然后,计时器的到期处理程序可以在超时到期时取消异步读取.这看起来像这样(从上面链接的示例中获取的片段):
std::size_t receive(const boost::asio::mutable_buffer& buffer,
boost::posix_time::time_duration timeout, boost::system::error_code& ec)
{
// Set a deadline for the asynchronous operation.
deadline_.expires_from_now(timeout);
// Set up the variables that receive the result of the asynchronous
// operation. The error code is set to would_block to signal that the
// operation is incomplete. Asio guarantees that its asynchronous
// operations will never …Run Code Online (Sandbox Code Playgroud) 以下是我的代码
boost::asio::io_service io;
boost::asio::ip::tcp::acceptor::reuse_address option(true);
boost::asio::ip::tcp::acceptor accept(io);
boost::asio::ip::tcp::resolver resolver(io);
boost::asio::ip::tcp::resolver::query query("0.0.0.0", "8080");
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
accept.open(endpoint.protocol());
accept.set_option(option);
accept.bind(endpoint);
accept.listen(30);
boost::asio::ip::tcp::socket ps(io);
accept.accept(ps);
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
//setsockopt(ps.native(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
setsockopt(ps.native(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
char buf[1024];
ps.async_receive(boost::asio::buffer(buf, 1024), boost::bind(fun));
io.run();
Run Code Online (Sandbox Code Playgroud)
当我使用Telnet连接但不发送数据时,它不会与Telnet超时断开连接.是否需要设置setsockopt?谢谢!
我已将SO_RCVTIMEO修改为SO_SNDTIMEO.仍无法在指定时间内超时