[英]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. 每当您在计时器上收到一些数据时,您可以使用cancel和
expires_from_now
重置倒计时,当计时器到期时,您可以关闭套接字或采取其他一些操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.