Convert Figma logo to code with AI

boostorg logobeast

HTTP and WebSocket built on Boost.Asio in C++11

4,316
634
4,316
107

Top Related Projects

A collection of C++ HTTP libraries including an easy to use HTTP server.

A C++ header-only HTTP/HTTPS server and client library

The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.

Simple, secure & standards compliant web server for the most demanding of applications

A curated list of awesome C++ (or C) frameworks, libraries, resources, and shiny things. Inspired by awesome-... stuff.

42,154

JSON for Modern C++

Quick Overview

The Boost.Beast library is a C++ HTTP and WebSocket protocol implementation, designed to be highly customizable and efficient. It is part of the Boost C++ Libraries, a collection of peer-reviewed, open-source libraries that provide a wide range of functionality for C++ developers.

Pros

  • High Performance: Boost.Beast is built on top of Boost.Asio, a highly performant networking library, and is designed to be efficient and scalable.
  • Flexibility: The library is highly customizable, allowing developers to tailor it to their specific needs and use cases.
  • Cross-Platform: Boost.Beast is cross-platform, supporting a wide range of operating systems and compilers.
  • Comprehensive Documentation: The project has extensive documentation, including tutorials, examples, and API reference, making it easy for developers to get started and understand the library.

Cons

  • Complexity: The library can be complex, with a steep learning curve, especially for developers new to Boost or low-level networking programming.
  • Dependency on Boost: Boost.Beast is a part of the Boost C++ Libraries, which means that developers need to have Boost installed and configured in their development environment.
  • Limited Standalone Usage: While Boost.Beast can be used as a standalone library, it is primarily designed to be used within the Boost ecosystem, which may limit its adoption in projects that do not use other Boost libraries.
  • Potential Performance Overhead: The flexibility and customizability of Boost.Beast may come with some performance overhead, depending on the specific use case and configuration.

Code Examples

Here are a few code examples demonstrating the usage of Boost.Beast:

  1. HTTP Server:
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>

namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = net::ip::tcp;

int main() {
    try {
        net::io_context ioc;
        tcp::acceptor acceptor(ioc, {tcp::v4(), 8080});
        tcp::socket socket(ioc);
        acceptor.accept(socket);

        http::request<http::string_body> req;
        http::read(socket, beast::flat_buffer(), req);

        http::response<http::string_body> res;
        res.version(req.version());
        res.result(http::status::ok);
        res.set(http::field::server, "Boost.Beast");
        res.set(http::field::content_type, "text/plain");
        res.body() = "Hello, world!";
        res.prepare_payload();

        http::write(socket, res);
    } catch (std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

This code example demonstrates how to create a simple HTTP server using Boost.Beast.

  1. WebSocket Server:
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>

namespace beast = boost::beast;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = net::ip::tcp;

int main() {
    try {
        net::io_context ioc;
        tcp::acceptor acceptor(ioc, {tcp::v4(), 8080});
        tcp::socket socket(ioc);
        acceptor.accept(socket);

        websocket::stream<tcp::socket&> ws(socket);
        ws.accept();

        beast::flat_buffer buffer;
        ws.read(buffer);

        std::string message = beast::buffers_to_string(buffer.data());
        std::cout

Competitor Comparisons

A collection of C++ HTTP libraries including an easy to use HTTP server.

Pros of Proxygen

  • More comprehensive HTTP server framework with additional features like load balancing and traffic shaping
  • Better suited for large-scale, high-performance applications
  • Actively maintained by Facebook, with frequent updates and improvements

Cons of Proxygen

  • Steeper learning curve due to its complexity and extensive feature set
  • Heavier resource footprint, which may be overkill for smaller projects
  • C++ only, while Beast supports both C++ and C

Code Comparison

Beast (HTTP request):

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);

Proxygen (HTTP request):

proxygen::HTTPMessage req;
req.setMethod(proxygen::HTTPMethod::GET);
req.setURL(target);
req.getHeaders().set(proxygen::HTTP_HEADER_HOST, host);
req.getHeaders().set(proxygen::HTTP_HEADER_USER_AGENT, "proxygen");

Both libraries provide similar functionality for creating HTTP requests, but Proxygen uses a more object-oriented approach with dedicated classes for HTTP messages and headers.

A C++ header-only HTTP/HTTPS server and client library

Pros of cpp-httplib

  • Lightweight and header-only library, easy to integrate
  • Simple API, making it straightforward to use for basic HTTP operations
  • Cross-platform support (Windows, macOS, Linux)

Cons of cpp-httplib

  • Limited feature set compared to Beast's comprehensive offerings
  • May not be as performant for high-load scenarios
  • Less extensive documentation and community support

Code Comparison

cpp-httplib:

#include <httplib.h>

int main() {
    httplib::Server svr;
    svr.Get("/", [](const httplib::Request&, httplib::Response& res) {
        res.set_content("Hello, World!", "text/plain");
    });
    svr.listen("localhost", 8080);
}

Beast:

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio.hpp>

namespace http = boost::beast::http;

int main() {
    boost::asio::io_context ioc;
    boost::asio::ip::tcp::acceptor acceptor(ioc, {boost::asio::ip::tcp::v4(), 8080});
    // Additional setup and request handling code required
}

Beast offers more flexibility and power but requires more setup code. cpp-httplib provides a simpler interface for basic HTTP server functionality, making it easier to get started quickly. However, Beast's comprehensive feature set and integration with Boost libraries make it more suitable for complex, high-performance applications.

The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.

Pros of cpprestsdk

  • Cross-platform support for Windows, Linux, macOS, and mobile platforms
  • Built-in support for JSON parsing and manipulation
  • Extensive documentation and Microsoft backing

Cons of cpprestsdk

  • Larger footprint and potentially slower performance
  • Less flexible for low-level networking tasks
  • Steeper learning curve for developers new to asynchronous programming

Code Comparison

Beast:

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/config.hpp>

cpprestsdk:

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/json.h>

Beast focuses on providing low-level HTTP and WebSocket functionality, while cpprestsdk offers a higher-level abstraction for RESTful services. Beast's approach allows for more fine-grained control over network operations, whereas cpprestsdk simplifies common tasks like JSON handling and HTTP requests.

Beast is part of the Boost ecosystem, benefiting from its extensive testing and community support. cpprestsdk, backed by Microsoft, offers broader platform support and integration with other Microsoft technologies.

Developers should choose based on their specific needs: Beast for performance-critical or low-level networking tasks, and cpprestsdk for rapid development of cross-platform REST clients and servers with built-in JSON support.

Simple, secure & standards compliant web server for the most demanding of applications

Pros of uWebSockets

  • Significantly higher performance and lower latency
  • Smaller memory footprint and resource usage
  • Built-in support for WebSocket compression

Cons of uWebSockets

  • Less comprehensive documentation and examples
  • Smaller community and ecosystem compared to Beast
  • More focused on WebSockets, less versatile for general HTTP handling

Code Comparison

Beast:

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>

namespace beast = boost::beast;
namespace websocket = beast::websocket;

websocket::stream<tcp::socket> ws{ioc};
ws.accept();
ws.write(net::buffer(std::string("Hello, WebSocket!")));

uWebSockets:

#include <uwebsockets/App.h>

uWS::App().ws<PerSocketData>("/*", {
    .message = [](auto *ws, std::string_view message, uWS::OpCode opCode) {
        ws->send("Hello, WebSocket!", opCode);
    }
}).listen(9001, [](auto *listen_socket) {
    if (listen_socket) {
        std::cout << "Listening on port " << 9001 << std::endl;
    }
}).run();

Both libraries offer WebSocket functionality, but uWebSockets provides a more concise API for setting up a WebSocket server. Beast, being part of Boost, offers a more traditional C++ approach with greater flexibility for low-level control.

A curated list of awesome C++ (or C) frameworks, libraries, resources, and shiny things. Inspired by awesome-... stuff.

Pros of awesome-cpp

  • Comprehensive collection of C++ resources and libraries
  • Regularly updated with community contributions
  • Covers a wide range of C++ topics and use cases

Cons of awesome-cpp

  • Not a functional library itself, just a curated list
  • May include outdated or less maintained projects
  • Requires additional effort to evaluate and integrate listed resources

Code comparison

Not applicable, as awesome-cpp is a curated list and doesn't contain actual code. Beast, on the other hand, is a functional library. Here's a simple example of using Beast:

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>

namespace http = boost::beast::http;

http::request<http::string_body> req{http::verb::get, "/", 11};
req.set(http::field::host, "example.com");
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

Summary

Beast is a C++ library for building HTTP and WebSocket applications, while awesome-cpp is a curated list of C++ resources. Beast provides actual functionality for network programming, whereas awesome-cpp serves as a valuable reference for discovering various C++ tools and libraries, including networking solutions like Beast itself.

42,154

JSON for Modern C++

Pros of json

  • Lightweight and header-only library, easy to integrate
  • Extensive documentation and examples
  • Wide language support (C++11 and later)

Cons of json

  • Limited to JSON parsing and manipulation
  • May have slower performance for large datasets
  • Lacks built-in networking capabilities

Code Comparison

json:

#include <nlohmann/json.hpp>
using json = nlohmann::json;

json j = {
  {"name", "John"},
  {"age", 30},
  {"city", "New York"}
};
std::string serialized = j.dump();

Beast:

#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
namespace http = boost::beast::http;

http::request<http::string_body> req{http::verb::get, "/api/data", 11};
req.set(http::field::host, "example.com");
req.set(http::field::user_agent, "Beast");

Beast is a more comprehensive networking library with HTTP and WebSocket support, while json focuses solely on JSON manipulation. Beast is part of the Boost ecosystem, offering integration with other Boost libraries. json is simpler to use for JSON-specific tasks but lacks networking features. Beast requires more setup but provides a complete solution for HTTP and WebSocket communication.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Boost.Beast Title

HTTP and WebSocket built on Boost.Asio in C++11

BranchLinux / WindowsCoverageDocumentationMatrix
masterBuild StatuscodecovDocumentationMatrix
developBuild StatuscodecovDocumentationMatrix

Contents

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.

Appearances

CppCon 2018Bishop Fox 2018
BeastBeast Security Review
CppCon 2017CppCast 2017CppCon 2016
BeastVinnie FalcoBeast

Description

This software is in its first official release. Interfaces may change in response to user feedback. For recent changes see the CHANGELOG.

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)

Building

Beast is header-only. To use it just add the necessary #include line to your source files, like this:

#include <boost/beast.hpp>

If you use coroutines you'll need to link with the Boost.Coroutine library. Please visit the Boost documentation for instructions on how to do this for your particular build system.

GitHub

To use the latest official release of Beast, simply obtain the latest Boost distribution and follow the instructions for integrating it into your development environment. If you wish to build the examples and tests, or if you wish to preview upcoming changes and features, it is suggested to clone the "Boost superproject" and work with Beast "in-tree" (meaning, the libs/beast subdirectory of the superproject).

The official repository contains the following branches:

  • master This holds the most recent snapshot with code that is known to be stable.

  • develop This holds the most recent snapshot. It may contain unstable code.

Each of these branches requires a corresponding Boost branch and all of its subprojects. For example, if you wish to use the master branch version of Beast, you should clone the Boost superproject, switch to the master branch in the superproject and acquire all the Boost libraries corresponding to that branch including Beast.

To clone the superproject locally, and switch into the main project's directory use:

git clone --recursive https://github.com/boostorg/boost.git
cd boost

"bjam" is used to build Beast and the Boost libraries. On a non-Windows system use this command to build bjam:

./bootstrap.sh

From a Windows command line, build bjam using this command:

.\BOOTSTRAP.BAT

Building tests and examples

Building tests and examples requires OpenSSL installed. If OpenSSL is installed in a non-system location, you will need to copy the user-config.jam file into your home directory and set the OPENSSL_ROOT environment variable to the path that contains an installation of OpenSSL.

Ubuntu/Debian

If installed into a system directory, OpenSSL will be automatically found and used.

sudo apt install libssl-dev

Windows

Replace path in the following code snippets with the path you installed vcpkg to. Examples assume a 32-bit build, if you build a 64-bit version replace x32-windows with x64-windows in the path.

vcpkg install openssl --triplet x32-windows
SET OPENSSL_ROOT=path\installed\x32-windows
  • Using vcpkg and PowerShell:
vcpkg install openssl --triplet x32-windows
$env:OPENSSL_ROOT = "path\x32-windows"
vcpkg.exe install openssl --triplet x32-windows
export OPENSSL_ROOT=path/x32-windows

Mac OS

Using brew:

brew install openssl
export OPENSSL_ROOT=$(brew --prefix openssl)
# install bjam tool user specific configuration file to read OPENSSL_ROOT
# see https://www.bfgroup.xyz/b2/manual/release/index.html
cp ./libs/beast/tools/user-config.jam $HOME

Make sure the bjam tool (also called "b2") is available in the path your shell uses to find executables. The Beast project is located in "libs/beast" relative to the directory containing the Boot superproject. To build the Beast tests, examples, and documentation use these commands:

export PATH=$PWD:$PATH
b2 -j2 libs/beast/test cxxstd=11      # bjam must be in your $PATH
b2 -j2 libs/beast/example cxxstd=11   # "-j2" means use two processors
b2 libs/beast/doc                     # Doxygen and Saxon are required for this

Additional instructions for configuring, using, and building libraries in superproject may be found in the Boost Wiki.

Visual Studio

CMake may be used to generate a very nice Visual Studio solution and a set of Visual Studio project files using these commands:

cd libs/beast
mkdir bin
cd bin
cmake -G "Visual Studio 17 2022" -A Win32 ..  # for 32-bit Windows builds, or
cmake -G "Visual Studio 17 2022" -A x64 ..    # for 64-bit Windows builds

The files in the repository are laid out thusly:

./
    bin/            Create this to hold executables and project files
    bin64/          Create this to hold 64-bit Windows executables and project files
    doc/            Source code and scripts for the documentation
    include/        Where the header files are located
    example/        Self contained example programs
    meta/           Metadata for Boost integration
    test/           The unit tests for Beast
    tools/          Scripts used for CI testing

Usage

These examples are complete, self-contained programs that you can build and run yourself (they are in the example directory).

https://www.boost.org/doc/libs/develop/libs/beast/doc/html/beast/quick_start.html

License

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)

Contact

Please report issues or questions here: https://github.com/boostorg/beast/issues


Contributing (We Need Your Help!)

If you would like to contribute to Beast and help us maintain high quality, consider performing code reviews on active pull requests. Any feedback from users and stakeholders, even simple questions about how things work or why they were done a certain way, carries value and can be used to improve the library. Code review provides these benefits:

  • Identify bugs
  • Documentation proof-reading
  • Adjust interfaces to suit use-cases
  • Simplify code

You can look through the Closed pull requests to get an idea of how reviews are performed. To give a code review just sign in with your GitHub account and then add comments to any open pull requests below, don't be shy!

https://github.com/boostorg/beast/pulls

Here are some resources to learn more about code reviews:

Beast thrives on code reviews and any sort of feedback from users and stakeholders about its interfaces. Even if you just have questions, asking them in the code review or in issues provides valuable information that can be used to improve the library - do not hesitate, no question is insignificant or unimportant!