You can use something like this.
try change stream.connect(results)
to
auto Future = stream.async_connect(endpoint, net::use_future);
if(Future.wait_for(std::chrono::seconds(1)) == std::future_status::timeout){
std::cout<<"timed_out";
....
}else {
}
Bunch of things to note:
1)You may need below header files
#include<boost/asio/use_future.hpp>
#include<chrono>
#include<future>
2) Since you are asyc_* initiating; you need to call ioc.run();
3) You need an another thread to execute ioc.run();
as we are mocking synchronous via asynchronous-- someone have to run the event-loop.
Another approach: you can explicitly set the socket option using its native handle (I've never done it). But before doing that, read this answer https://mcmap.net/q/345681/-how-to-set-a-timeout-on-blocking-sockets-in-boost-asio
const int timeout = 200;
::setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof timeout);//SO_SNDTIMEO for send ops
https://linux.die.net/man/7/socket
SO_RCVTIMEO and SO_SNDTIMEO Specify the receiving or sending timeouts
until reporting an error. The argument is a struct timeval. If an
input or output function blocks for this period of time, and data has
been sent or received, the return value of that function will be the
amount of data transferred; if no data has been transferred and the
timeout has been reached then -1 is returned with errno set to EAGAIN
or EWOULDBLOCK, or EINPROGRESS (for connect(2)) just as if the socket
was specified to be nonblocking. If the timeout is set to zero (the
default) then the operation will never timeout. Timeouts only have
effect for system calls that perform socket I/O (e.g., read(2),
recvmsg(2), send(2), sendmsg(2)); timeouts have no effect for
select(2), poll(2), epoll_wait(2), and so on.
std::future
and itswait_for
member function? asio library (wrapped by beast) supportsuse_future
which emulates blocking behaviour as synchronous clients. – Archicarp