如何打印 WebSocket HTTP 升级请求?

How to print the WebSocket HTTP Upgrade Request?

参考: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

问题> 根据示例websocket_client_sync.cpp,哪个函数用于发送与上图类似的 HTTP 升级请求以及如何打印请求如上所示?

谢谢

这是重复的,但我无法将其标记为重复,因为此答案从未被接受¹:

boost async ws server checking client information

简而言之,使用 accept 的重载,它接受您之前阅读过的请求对象。

链接的答案有完整的现场演示。


¹ 对 Stack overflow 的回答有时会非常吃力不讨好

更新

对于评论,我很抱歉最初错过了 client/server 区别。客户端在 handshake 上有一个类似的重载,允许您检查升级 response:

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

打印例如

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

但是,请求并没有直接公开。我想最好用网络数据包嗅探器或从服务器端进行监控。如果目标是 操纵 升级请求,您应该使用 RequestDecorator.

PS:我刚刚检查了请求装饰器 is applied nearly-at-the-end(虽然一些与 per-message-deflate 相关的东西可能会在稍后的 handshake_op 中添加)。因此,您可能只满足于提供一个检查请求的装饰器:

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;

打印出例如

--- 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=