简体   繁体   English

Boost :: asio socket - 如何在“超时”中使read_some'throw'?

[英]Boost::asio socket - how to make read_some 'throw' in “timeout”?

So normaly we do something like this socket.read_some(boost::asio::buffer(buffer, buffer_size)); 所以我们通常做类似socket.read_some(boost::asio::buffer(buffer, buffer_size)); but how to make it throw an exeption in case of read has not started for some time longer than say 333 seconds? 但是如果让它在读取的情况下抛出一段时间还没有开始一段时间比333秒更长?

You should consider using async_read_some instead of read_some , since it allows you to start a new background timer simultaneously with the read. 您应该考虑使用async_read_some而不是read_some ,因为它允许您在读取的同时启动新的后台计时器。 Then, to create a new timer for each new socket you do: 然后,为每个新套接字创建一个新计时器:

boost::asio::io_service io_service;

time_t_timer timer(io_service);

timer.expires_from_now(333);
std::cout << "Starting asynchronous wait\n";
timer.async_wait(&handle_timeout);
io_service.run();

You will have two asyncronous calls waiting on background. 您将在后台等待两个异步调用。

Whenever you receive some data on the timer you can reset the countdown using cancel and expires_from_now , and when the timer expires you can close the socket or take some other action. 每当您在计时器上收到一些数据时,您可以使用cancelexpires_from_now重置倒计时,当计时器到期时,您可以关闭套接字或采取其他一些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用boost :: asio :: read_some实现超时? - How to implement timeout with using boost::asio::read_some? Boost.Asio read_some:文件结尾错误 - Boost.Asio read_some: End of file error 我们如何从 boost::asio::tcp::ip::read_some 调用中依次接收多个数据? - How can we sequentially receive multiple data from boost::asio::tcp::ip::read_some calls? 如何从一个套接字读取asio缓冲区的数据,例如说“ 1”字节,而不是从另一个套接字读取“ read_some”呢? - How to read to asio buffer say `1` byte from one socket and than `read_some` more from another? 在使用boost :: asio read_some()函数时替代std :: array,在read_some()函数调用时boost :: array崩溃 - Substitute for std::array when using boost::asio read_some() function, boost::array crashes at read_some() function call 将 asio read_some 转换为异步版本 - Converting asio read_some to async version C ++ Boost Asio串行端口同步read_some是否无限期阻塞? - C++ Boost Asio Serial Port Synchronous read_some Blocking Indefinitely? 如何在接收 boost::asio udp::socket 时超时? - How to make a timeout at receiving in boost::asio udp::socket? 提升read_some函数丢失数据 - boost read_some function lost data 如何使用带有io_contexts的boost :: asio从超时的套接字中读取? - How to read from a socket with a timeout using boost::asio with io_contexts?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM