Skip to content

Instantly share code, notes, and snippets.

@Spongman
Last active February 23, 2024 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Spongman/c1b2cfa87db43edf409ba90b7684fa7e to your computer and use it in GitHub Desktop.
Save Spongman/c1b2cfa87db43edf409ba90b7684fa7e to your computer and use it in GitHub Desktop.
simple c++ web server with multi-threading, async i/o and keep-alives.
#include <boost/beast.hpp>
#include <boost/asio.hpp>
namespace ip = boost::asio::ip;
namespace http = boost::beast::http;
int main() {
boost::asio::thread_pool ioc;
ip::tcp::acceptor acceptor{ioc, ip::tcp::endpoint{ip::address::from_string("127.0.0.1"), 9999}};
while(true) {
ip::tcp::socket socket{ioc};
acceptor.accept(socket);
co_spawn(ioc, [socket = std::move(socket)]() mutable -> boost::asio::awaitable<void> {
for (bool keep_alive = true; keep_alive; ) {
http::request<http::string_body> req;
boost::beast::flat_buffer buffer;
co_await http::async_read(socket, buffer, req, boost::asio::use_awaitable);
keep_alive = req.keep_alive();
auto path = "htdir" + std::string{req.target()};
if (req.target().ends_with("/")) path += "index.html";
boost::beast::error_code ec;
http::response<http::file_body> resp;
resp.body().open(path.c_str(), boost::beast::file_mode::scan, ec);
if (resp.body().is_open()) {
resp.keep_alive(keep_alive);
resp.prepare_payload();
co_await http::async_write(socket, resp, boost::asio::use_awaitable);
}
}
}, boost::asio::detached);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment