Beast Logo

PrevUpHomeNext

Algorithms

Algorithms are provided to serialize and deserialize HTTP/1 messages on streams.

Asynchronous versions of these algorithms are also available:

Using Sockets

The free function algorithms are modeled after Boost.Asio to send and receive messages on TCP/IP sockets, SSL streams, or any object which meets the Boost.Asio type requirements (SyncReadStream, SyncWriteStream, AsyncReadStream, and AsyncWriteStream depending on the types of operations performed). To send messages synchronously, use one of the write functions:

void send_request(boost::asio::ip::tcp::socket& sock)
{
    request<empty_body> req;
    req.version = 11;
    req.method = "GET";
    req.url = "/index.html";
    ...
    write(sock, req); // Throws exception on error
    ...
    // Alternatively
    boost::system::error:code ec;
    write(sock, req, ec);
    if(ec)
        std::cerr << "error writing http message: " << ec.message();
}

An asynchronous interface is available:

void handle_write(boost::system::error_code);
...
request<empty_body> req;
...
async_write(sock, req, std::bind(&handle_write, std::placeholders::_1));

When the implementation reads messages from a socket, it can read bytes lying after the end of the message if they are present (the alternative is to read a single byte at a time which is unsuitable for performance reasons). To store and re-use these extra bytes on subsequent messages, the read interface requires an additional parameter: a DynamicBuffer object. This example reads a message from the socket, with the extra bytes stored in the streambuf parameter for use in a subsequent call to read:

boost::asio::streambuf sb;
...
response<string_body> res;
read(sock, sb, res); // Throws exception on error
...
// Alternatively
boost::system::error:code ec;
read(sock, sb, res, ec);
if(ec)
    std::cerr << "error reading http message: " << ec.message();

As with the write function, an asynchronous interface is available. The stream buffer parameter must remain valid until the completion handler is called:

void handle_read(boost::system::error_code);
...
boost::asio::streambuf sb;
response<string_body> res;
...
async_read(sock, res, std::bind(&handle_read, std::placeholders::_1));

An alternative to using a boost::asio::streambuf is to use a streambuf, which meets the requirements of DynamicBuffer and is optimized for performance:

void handle_read(boost::system::error_code);
...
beast::streambuf sb;
response<string_body> res;
read(sock, sb, res);

The read implementation can use any object meeting the requirements of DynamicBuffer, allowing callers to define custom memory management strategies used by the implementation.


PrevUpHomeNext