Search code examples
c++network-programmingboost

Async accept not calling handler


I'm trying to make a simple socket server that handles multiple clients using the boost server. But I'm having a problem where the handler for the async_accept function is not invoking the handler that I specified. It's probably an easy fix, but I'm not really used to the Boost framework yet.

    #include <boost/asio.hpp>
    #include <boost/thread/thread.hpp>
    #include <iostream>

    using namespace boost::asio;
    using ip::tcp;
    using std::cout;
    using std::endl;
    using std::string;
    void accept_handler(const boost::system::error_code& error) {
    if (!error) {
    std::cout << "Success";
    } else {
    std::cout << "Failed";
      
    }
    }

    void server(int port) {
    boost::asio::io_service io_service;
    // listen for new connection
    tcp::acceptor acceptor_(io_service, tcp::endpoint(tcp::v4(), port));
    std::cout << "Listening for Connection\n";
    // socket creation
    tcp::socket socket_(io_service);
    // waiting for the connection
    std::cout << "Waiting for Clients\n";
    acceptor_.async_accept(socket_, accept_handler);
}

The things I tried were looking at the documentation of the boost framework, which said

"This function is used to ask the io_service to execute the given handler, but without allowing the io_service to call the handler from inside this function."

To sum it up, the async_accept function does call the handler automatically. So I'm trying to figure out how I could invoke the function automatically.


Solution

  • You have an async operation but nothing to run your io service. The simplest fix is to add it immediately:

    void server(int port) {
        asio::io_service io_service;
        // listen for new connection
        tcp::acceptor acceptor_(io_service, tcp::endpoint(tcp::v4(), port));
        std::cout << "Listening for Connection\n";
        // socket creation
        tcp::socket socket_(io_service);
        // waiting for the connection
        std::cout << "Waiting for Clients\n";
        acceptor_.async_accept(socket_, accept_handler);
    
        io_service.run();
    }
    

    Keep in mind that unless the accept_handler posts more async work, the service will complete and you'd need to restart it to do new work.