简体   繁体   中英

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)); but how to make it throw an exeption in case of read has not started for some time longer than say 333 seconds?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM