3

How do i check client information as user-agent from boost async web socket server ?

I have checked: https://www.boost.org/doc/libs/develop/libs/beast/example/websocket/server/async/websocket_server_async.cpp

It was my only referance.

sehe
  • 374,641
  • 47
  • 450
  • 633
SASA
  • 41
  • 4

1 Answers1

0

Instead of the async_accept on the websocket here:

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

You could read a HTTP request instead and call the third overload instead:

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

And then outside 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()));
}

This gives you the opportunity to do stuff inside on_upgrade that inspects the upgrade request:

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()));
}

Indeed using wscat as client:

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

Causes our Beast server to print out:

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: 
sehe
  • 374,641
  • 47
  • 450
  • 633