Search code examples
c++websocketwebsocket++

Websocketpp simple HTTP client


I use the excellent websocketpp library to provide a Websockets (and HTTP) server in a C++ application. I also need a HTTP client in the same app to connect to REST APIs. I have been attempting this in websocketpp also, but so far I have had little success. The following preliminary attempt gives me this log output:

[2015-03-06 18:01:18] [connect] Successful connection
[2015-03-06 18:01:18] [error] Server handshake response error: websocketpp.processor:20 (Invalid HTTP status.)
[2015-03-06 18:01:18] [disconnect] Failed: Invalid HTTP status.

This suggests my http_ handler method may need something more. Any advice would be appreciated. The websocketpp docs and examples don't seem to include a simple HTTP client.

#define _WEBSOCKETPP_CPP11_STL_
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>
#include <websocketpp/common/thread.hpp>

namespace {

using namespace websocketpp;
typedef client<websocketpp::config::asio_client> client;

class Client {
public:

    Client(void){
        client_.init_asio();
        client_.set_http_handler(bind(&Client::http_,this,_1));
    }

    std::string get(const std::string& url) {
        websocketpp::lib::error_code error;
        client::connection_ptr con = client_.get_connection(url,error);
        if(error) std::runtime_error("Unable to connnect.\n  url: "+url+"\n  message: "+error.message());
        client_.connect(con);
        websocketpp::lib::thread asio_thread(&client::run, &client_);
        asio_thread.join();
        return data_;
    }

private:

    void http_(connection_hdl hdl){
        std::cout<<"Connected\n";
        data_ = "http payload";
    }

    client client_;
    std::string data_;
};

}

int main(void){
    Client client;
    client.get("http://google.com/");
}

Solution

  • WebSocket++'s HTTP handling features are a convenience feature designed to allow WebSocket servers to serve HTTP responses in a limited capacity. WebSocket++ is not intended for use as a generic HTTP library and does not contain the ability to play the role of a (non-WebSocket) HTTP client.

    Using a separate library (such as cpp-netlib) for HTTP client functionality is a good solution.