欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c++ boost库下的beast单元库关于先发包头再发包体

程序员文章站 2022-06-01 09:17:54
...
#include <boost/beast/http.hpp>
#include <boost/asio.hpp>

using body_type = boost::beast::http::string_body;
using request_serializer = boost::beast::http::serializer<true, body_type>;
using stream_type = boost::asio::ip::tcp::socket;

void send_header(stream_type& strm, request_serializer& ser);
void send_rest(stream_type& strm, request_serializer& ser);

// 首先,发送标题
void send_header(stream_type& strm, request_serializer& ser)
{
    boost::beast::http::async_write_header(strm, ser, 
        [&](boost::beast::error_code ec, std::size_t)
        {
            if (!ec)
            {
                send_rest(strm, ser);
            }
            else
            {
                // handle error
            }
        });
}

// 如果标头发送成功,则发送其余消息
void send_rest(stream_type& strm, request_serializer& ser)
{
    boost::beast::http::async_write(strm, ser, 
        [](boost::beast::error_code ec, std::size_t)
        {
            if (!ec)
            {
                // 成功- ser 的生命周期现在可以结束
            }
            else
            {
                // handle error
            }
        });
}