Beast Logo

PrevUpHomeNext

Messages

After the WebSocket handshake is accomplished, callers may send and receive messages using the message oriented interface. This interface requires that all of the buffers representing the message are known ahead of time:

void echo(beast::websocket::stream<boost::asio::ip::tcp::socket>& ws)
{
    beast::multi_buffer b;
    beast::websocket::opcode::value op;
    ws.read(op, b);

    ws.set_option(beast::websocket::message_type{op});
    ws.write(b.data());
    sb.consume(b.size());
}
[Important] Important

Calls to set_option must be made from the same implicit or explicit strand as that used to perform other operations.

Frames

Some use-cases make it impractical or impossible to buffer the entire message ahead of time:

For these cases, the frame oriented interface may be used. This example reads and echoes a complete message using this interface:

void echo(beast::websocket::stream<boost::asio::ip::tcp::socket>& ws)
{
    beast::multi_buffer b;
    beast::websocket::frame_info fi;
    for(;;)
    {
        ws.read_frame(fi, b);
        if(fi.fin)
            break;
    }
    ws.set_option(beast::websocket::message_type{fi.op});
    beast::consuming_buffers<
        beast::multi_buffer::const_buffers_type> cb{b.data()};
    for(;;)
    {
        using boost::asio::buffer_size;
        std::size_t size = std::min(buffer_size(cb));
        if(size > 512)
        {
            ws.write_frame(false, beast::prepare_buffers(512, cb));
            cb.consume(512);
        }
        else
        {
            ws.write_frame(true, cb);
            break;
        }
    }
}

PrevUpHomeNext