3

如何从 boost 异步 Web 套接字服务器检查客户端信息作为用户代理?

我已经检查过: https ://www.boost.org/doc/libs/develop/libs/beast/example/websocket/server/async/websocket_server_async.cpp

这是我唯一的参考。

4

1 回答 1

0

而不是async_accept这里的websocket:

    // Accept the websocket handshake
    ws_.async_accept(
        beast::bind_front_handler(
            &session::on_accept,
            shared_from_this()));

您可以改为读取 HTTP 请求并调用第三个重载

    // read upgrade request
    http::async_read(ws_.next_layer(), buffer_, upgrade_request_,
            beast::bind_front_handler(
                &session::on_upgrade,
                shared_from_this()));

然后在外面on_run()

http::request<http::string_body> upgrade_request_;

void
on_upgrade(beast::error_code ec, size_t) {
    if(ec)
        return fail(ec, "upgrade");
    // Accept the websocket handshake
    ws_.async_accept(
        upgrade_request_,
        beast::bind_front_handler(&session::on_accept, shared_from_this()));
}

这使您有机会在内部执行on_upgrade检查升级请求的操作:

void
on_upgrade(beast::error_code ec, size_t) {
    if(ec)
        return fail(ec, "upgrade");

    std::cout << "Upgrade request user-agent: " << upgrade_request_[http::field::user_agent] << "\n";
    std::cout << "Upgrade request headers: " << upgrade_request_.base() << "\n";
    std::cout << "Upgrade request body: " << upgrade_request_.body() << "\n";

    // Accept the websocket handshake
    ws_.async_accept(
        upgrade_request_,
        beast::bind_front_handler(&session::on_accept, shared_from_this()));
}

确实使用 wscat 作为客户端:

wscat -c "ws://localhost:9797/" -H 'User-agent: Slartibartfast' 

导致我们的 Beast 服务器打印出来:

Upgrade request user-agent: Slartibartfast
Upgrade request headers: GET / HTTP/1.1
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: o6j5v6YeqI4vEJT6AiVTyA==
Connection: Upgrade
Upgrade: websocket
User-agent: Slartibartfast
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: localhost:9797


Upgrade request body: 
于 2022-02-24T02:03:46.420 回答