I am trying to simulate boost::asio::write
with timeout. Or you can say, I am trying to use boost::asio::async_write
with a timeout.
As I see, boost::asio::write
blocks until all data has been written & read on the other side. This kind of functionality certainly requires a timeout.
So, Reading through this simple answer here by Robert Hegner which demostrates how to do a boost::asio::async_read
with timeout, I am trying adapt the same logic for write by doing so:
size_t write_data_with_time_out() {
long time_out_secs = 2;
boost::optional<boost::system::error_code> timer_result;
boost::asio::deadline_timer timer(the_socket->get_io_service(), boost::posix_time::seconds(time_out_secs));
timer.expires_from_now();
timer.async_wait([&timer_result] (const boost::system::error_code& error) {
timer_result.reset(error);
});
boost::optional<boost::system::error_code> write_result;
size_t bytes_sent = 0;
boost::asio::async_write(*the_socket, boost::asio::buffer(the_buffer_to_write, the_buffer_to_write.size()), [&write_result, &bytes_sent] (const boost::system::error_code& error, auto size_received) {
write_result.reset(error);
bytes_sent = size_received;
});
the_socket->get_io_service().reset();
while (the_socket->get_io_service().run_one()) {
if (write_result) {
timer.cancel();
}
else if (timer_result) {
the_socket->cancel();
}
}
if (*write_result) {
return 0;
}
return bytes_sent;
}
Problem:
The logic works great for read but does not seem to work for write case. Reason is that while (the_socket->get_io_service().run_one())
gets hung after calling the_socket->cancel()
twice.
However, in the read case also the_socket->cancel()
is called twice & does not hang on the 3rd loop over of the while & returns out. Hence no issues with read.
Question:
Is my understanding wrong that same timeout logic would work for boost::asio::async_write
case? I think this same logic should work. There is something wrong I am doing which is what I need a suggestion on.
Additional info required if possible:
if boost::asio::read
& boost::asio::write
had a timeout parameter. I would not have been writing this extra. Seems like there have been a lot of requests to asio guys to introduce a timeout in their sync read & write functions. Like this one here.
Is there any scope for asio guys to address this request in near future?
I am doing a sync boost::asio::read
& boost::asio::write
on the same socket using a worker thread for which this works superb. All I am missing is this timeout functionality.
Environment:
My code runs on Linux
& MacOSX
with C++ 14 compiler. This question only concerns TCP sockets.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…