A WebSocket++ based server listens for HTTP (or HTTPS for secure WebSocket servers) connections as well as WebSocket ones. By default, such requests get an HTTP error response with status code 426/Upgrade required. A WebSocket++ endpoint may implement an http_handler instead to process these requests.

Example blocking http_handler

// Blocking HTTP Handler
void on_http(server * s, websocketpp::connection_hdl hdl) {
    server::connection_ptr con = s->get_con_from_hdl(hdl);
    std::stringstream output;
    output << "<!doctype html><html><body>You requested "
           << con->get_resource()
           << "</body></html>";
    // Set status to 200 rather than the default error code
    // Set body text to the HTML created above

Example non-blocking http_handler

The above handler will compute the entire HTTP response and send it immediately. Alternatively, your HTTP handler may ask WebSocket++ core to defer sending the response until a later time. This gives your program the chance to perform longer calculations or load data from slower files/databases without blocking other network operations. The example below demonstrates the usage of this style using an asynchronous operation and a lambda callback. You could also use a worker thread to process the request and send the response.

// Asynchronous HTTP Handler
void on_http(websocketpp::connection_hdl hdl) {
    endpoint::connection_ptr con = s->get_con_from_hdl(hdl);

    // Begin an asynchronous operation and pass as a callback a lambda that sets
    // up the appropriate response and sends it.
    asyncronous_function([con](int status) {
        if (status == -1) {
            con->set_body("An error occurred");
        } else {
            con->set_body("Hello World!");

Usage Notes / Warnings

WebSocket++ is tuned for fast non-blocking delivery of WebSocket messages. Its http handler is not designed to be a full featured or high performance HTTP solution. It is suitable for delivering error messages, flash policy files, dynamically generated status/admin pages for the server, and other small bits of HTML/javascript for low volume single page web applications that largely rely on WebSockets after the first page load.

If you intend to serve any high volume or HTTP resources or need modern HTTP features it is strongly recommended that you serve this traffic from dedicated HTTP server software like Apache or Ngnix.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.