Boost beast 使用例子

13 篇文章 3 订阅

最近接触到了Boost beast,这里记录一下。

 

Introduction

Beast is a C++ header-only library serving as a foundation for writing interoperable networking libraries by providing low-level HTTP/1, WebSocket, and networking protocol vocabulary types and algorithms using the consistent asynchronous model of Boost.Asio.

This library is designed for:

  • Symmetry: Algorithms are role-agnostic; build clients, servers, or both.

  • Ease of Use: Boost.Asio users will immediately understand Beast.

  • Flexibility: Users make the important decisions such as buffer or thread management.

  • Performance: Build applications handling thousands of connections or more.

  • Basis for Further Abstraction. Components are well-suited for building upon.

 

Requirements

This library is for programmers familiar with Boost.Asio. Users who wish to use asynchronous interfaces should already know how to create concurrent network programs using callbacks or coroutines.

  • C++11: Robust support for most language features.
  • Boost: Boost.Asio and some other parts of Boost.
  • OpenSSL: Required for using TLS/Secure sockets and examples/tests

When using Microsoft Visual C++, Visual Studio 2017 or later is required.

One of these components is required in order to build the tests and examples:

  • Properly configured bjam/b2
  • CMake 3.5.1 or later (Windows only)

 

http client例子:

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>

namespace beast = boost::beast;     // from <boost/beast.hpp>
namespace http = beast::http;       // from <boost/beast/http.hpp>
namespace net = boost::asio;        // from <boost/asio.hpp>
using tcp = net::ip::tcp;           // from <boost/asio/ip/tcp.hpp>

// Performs an HTTP GET and prints the response
int main(int argc, char** argv)
{
    try
    {
        // Check command line arguments.
        if(argc != 4 && argc != 5)
        {
            std::cerr <<
                "Usage: http-client-sync <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" <<
                "Example:\n" <<
                "    http-client-sync www.example.com 80 /\n" <<
                "    http-client-sync www.example.com 80 / 1.0\n";
            return EXIT_FAILURE;
        }
        auto const host = argv[1];
        auto const port = argv[2];
        auto const target = argv[3];
        int version = argc == 5 && !std::strcmp("1.0", argv[4]) ? 10 : 11;

        // The io_context is required for all I/O
        net::io_context ioc;

        // These objects perform our I/O
        tcp::resolver resolver(ioc);
        beast::tcp_stream stream(ioc);

        // Look up the domain name
        auto const results = resolver.resolve(host, port);

        // Make the connection on the IP address we get from a lookup
        stream.connect(results);

        // Set up an HTTP GET request message
        http::request<http::string_body> req{http::verb::get, target, version};
        req.set(http::field::host, host);
        req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

        // Send the HTTP request to the remote host
        http::write(stream, req);

        // This buffer is used for reading and must be persisted
        beast::flat_buffer buffer;

        // Declare a container to hold the response
        http::response<http::dynamic_body> res;

        // Receive the HTTP response
        http::read(stream, buffer, res);

        // Write the message to standard out
        std::cout << res << std::endl;

        // Gracefully close the socket
        beast::error_code ec;
        stream.socket().shutdown(tcp::socket::shutdown_both, ec);

        // not_connected happens sometimes
        // so don't bother reporting it.
        //
        if(ec && ec != beast::errc::not_connected)
            throw beast::system_error{ec};

        // If we get here then the connection is closed gracefully
    }
    catch(std::exception const& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

从例子看得出来,用起来还是方便。

 

https://www.boost.org/doc/libs/1_68_0/libs/beast/doc/html/index.html

https://github.com/boostorg/beast

使用Boost.Beast库解析分段的HTTP请求可以按照以下步骤进行: 1. 准备接收缓冲区:创建一个缓冲区,用于接收分的HTTP请求数据。 ```cpp boostbeast::flat_buffer buffer; ``` 2 创建一个HTTP请求解析器:使用`boost::beast::http::request_parser`类创建一个HTTP请求解析器对象。 ```cpp ::beast::http::request_parser<boost::beast::http::string_body> parser; ``` 3. 解析分段的HTTP请求:使用解析器对象的`write_some`方法来解析每个分段的HTTP请求数据。 ```cpp std::string requestSegment1 = "GET /path HTTP/1.1\r\n" "Host: example.com\r\n" "Content-Length: 10\r\n" "\r\n" "Segment1"; std::string requestSegment2 = "Segment2"; parser.write_some(boost::asio::buffer(requestSegment1), error_code); parser.write_some(boost::asio::buffer(requestSegment2), error_code); ``` 4. 检查解析状态:使用解析器对象的`is_done`方法来检查是否已完成解析。 ```cpp bool isDone = parser.is_done(); ``` 5. 获取解析结果:如果解析已完成,可以从解析器对象中获取HTTP请求的各个部分。 ```cpp boost::beast::http::request<boost::beast::http::string_body> httpRequest = parser.get(); std::string method = httpRequest.method_string().to_string(); std::string target = httpRequest.target().to_string(); // 其他请求头和请求体的处理 ``` 注意:上述代码只是一个简单示例,实际使用中可能需要更多的错误处理、循环接收分段数据等。 Boost.Beast库提供了更多高级的功能和灵活性,可以根据具体需求进行更复杂的HTTP请求解析。你可以参考Boost.Beast的官方文档和示例代码来获取更详细的信息和用法。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值