Search code examples
boostboost-beast-websocket

How to print the WebSocket HTTP Upgrade Request?


Reference: websocket_client_sync.cpp

Table 1.30. WebSocket HTTP Upgrade Request

GET / HTTP/1.1
Host: www.example.com
Upgrade: websocket
Connection: upgrade
Sec-WebSocket-Key: 2pGeTR0DsE4dfZs2pH+8MA==
Sec-WebSocket-Version: 13
User-Agent: Boost.Beast/216

Question> Based on the example websocket_client_sync.cpp, which function is used to send a HTTP Upgrade Request similar as the one shown above and how can I print the request shown above?

Thank you


Solution

  • This is a duplicate, but I can't mark it as such because this answer was never accepted¹:

    boost async ws server checking client information

    In short use the overload of accept that that takes a request object that you have previously read.

    The linked answer has a complete live demo.


    ¹ answering on Stack overflow can be pretty thankless at times

    UPDATE

    To the comment, I apologize for missing the client/server distinction initially. The client has a similar overload on handshake that allows you to inspect the upgrade response:

    http::response<http::string_body> res;
    ws.handshake(res, host, "/");
    std::cout << res;
    

    Printing e.g.

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: /wp5bsjYquNsAIhi4lKoIuDm0TY=
    

    However, the request is not directly exposed. I suppose it's best monitored with a network packet sniffer or from the server side. If the goal is to manipulate the upgrade request, you should use a RequestDecorator.

    PS: I just checked and the request decorator is applied nearly-at-the-end (although some things related to per-message-deflate might be added on later in the handshake_op). So you might be content with just supplying a decorator that inspects the request:

    http::response<http::string_body> res;
    ws.set_option(websocket::stream_base::decorator(
        [](http::request<http::empty_body>& req) {
            std::cout << "--- Upgrade request: " << req << std::endl;
        }));
    ws.handshake(res, host, "/");
    std::cout << "--- Upgrade response: " << res << std::endl;
    

    Which prints e.g.

    --- Upgrade request: GET / HTTP/1.1
    Host: localhost:10000
    Upgrade: websocket
    Connection: upgrade
    Sec-WebSocket-Key: Quyn+IEvycAhcRtlvPIS4A==
    Sec-WebSocket-Version: 13
    
    
    --- Upgrade response: HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: aRDrnkHhNfaPqGdsisX51rjj+fI=