Search code examples
c++cpp-netlib

How close http connection with cpp-netlib?


When running the Cpp-netlib (version 0.11-rc1) [edit (addition)] code copied from [/edit] HttpClient example does not finish.

I assume it's because the connection is left open. 1. Is my assumption correct? 2. Does the connection have to be closed manually? 3. If so, how can the connection be accessed?


Solution

  • The Cpp-netlib http_client appears to use an asio::io_service that keeps running.

    To finish a HttpClient program use asio::io_service::stop().

    To be able to access the io_service that http_client uses:

    1. create an io_service instance;
    2. supply it to http_client via http_client_options; and
    3. when the program needs to finish, call stop() on the io_service-instance.

    The cppnetlib example client becomes:

    #include <boost/network/protocol/http/client.hpp>
    #include <boost/asio/io_service.hpp>
    #include <boost/shared_ptr.hpp>
    
    int main(int argc, char*[] argv)
    {
        using namespace boost::network;
        using namespace boost::network::http;
        using namespace boost::asio;     // LINE ADDED
    
        client::request request_("http://127.0.0.1:8000/");
        request_ << header("Connection", "close");
    
        // ADDED / MODIFIED
        boost::shared_ptr<io_service> io_service_ = boost::make_shared<io_service>();
        client client_(client::options()
                               .io_service(io_service_));
        // END ADDED
    
        client::response response_ = client_.get(request_);
        std::string body_ = body(response_);
    
        io_service_->stop();             // LINE ADDED
    }
    

    (see https://github.com/kaspervandenberg/https-tryout/blob/e8a918c5aa8efaaff3a37ac339bf68d132c6d2d6/httpClient.cxx for a full example.)