Beast Logo

PrevUpHomeNext

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::streambuf sb;
    beast::websocket::frame_info fi;
    for(;;)
    {
        ws.read_frame(fi, sb);
        if(fi.fin)
            break;
    }
    ws.set_option(beast::websocket::message_type{fi.op});
    beast::consuming_buffers<
        beast::streambuf::const_buffers_type> cb{sb.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