user0000001
user0000001

Reputation: 2233

Standalone asio async_connect not firing off bound handler

I have followed the documentation and examples provided by the boost asio implementation but not having any luck after connecting my client to the server. Regardless of success or failure, the handler is never called. I have verified that the server is receiving and accepting the connection from the client but nothing happens on the clients end to indicate success.

void ssl_writer::main_thread() {
    using namespace std::placeholders;
    using namespace asio::ip;

    tcp::resolver resolver(io_context);
    tcp::resolver::query query("192.168.170.115", "8591");
    tcp::resolver::iterator endpointer_iterator = resolver.resolve(query);

    io_context.run();

    std::cout << "connecting...";
    asio::async_connect(socket.lowest_layer(), endpointer_iterator, std::bind(&ssl_writer::handle_connect, this, _1));
}

//...

void ssl_writer::handle_connect(const std::error_code& error) {
    if (!error) {
        std::cout << "connected!";
    }
    else {
        std::cout << "failed!";
    }
}

Upvotes: 1

Views: 1445

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36488

io_context::run() processes handlers until there are no more handlers to process. As you haven't yet run any asynchronous calls there are no handlers and run returns immediately.

In this simple example you need to call io_context::run() after async_connect, in more complex programs you would normally create a worker thread to call io_context::run() and create an instance of boost::asio::executor_work_guard to prevent the io_context running out of work.

Upvotes: 1

Related Questions