I am using the asio
library and I am trying to connect to a socket.
Sometimes, the socket may take a very long time to connect. In that case, i just want to cancel the connection.
I am attempting to use std::future
and asio::use_future
with
asynchronous operations to do that. My idea is that i will call the asio::ip::tcp::socket
's member function async_connect()
with asio::use_future()
and then the wait_for()
to wait for the std::future
and check if it is ready or timed out.
If it is timed out I will cancel (return false) and if it is ready, I will continue the work. However, if I attempt to use wait_for()
and wait for the operation it will never be ready (it almost seems as if it is never run, but not sure how to verify that). Running the same code without using the std::future
seems to work fine, but I won't be able to enforce a timeout.
This is the code I tried.
asio::ip::tcp::endpoint endpoint(asio::ip::make_address(peer.address, ec), peer.port);
if (ec)
{
std::cout << ec.message() << std::endl;
return false;
}
asio::io_context context;
asio::ip::tcp::socket socket{context};
std::chrono::milliseconds span(100);
std::future<void> connect_status = socket.async_connect(endpoint, asio::use_future);
if (connect_status.wait_for(span) == std::future_status::timeout)
return false;
connect_status.get();