I'm trying to write a simple http server. while beast::http::read is working as respected, The async version does not call the handler at all (when trying to get http://localhost:8080/)
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
namespace asio = boost::asio;
namespace beast = boost::beast;
using tcp = asio::ip::tcp;
int main()
{
asio::io_context m_io_context;
tcp::acceptor m_acceptor(m_io_context, {tcp::v4(), 8080});
tcp::socket m_socket(m_io_context);
beast::flat_buffer buffer;
beast::http::request<beast::http::string_body> request;
m_acceptor.accept(m_socket);
while (true)
{
// Do something...
//beast::http::read(m_socket, buffer, request); // This works well
beast::http::async_read(
m_socket, buffer, request,
[](const beast::error_code& ec, std::size_t bytes_transferred)
{
// This function is never being called!!
// ...
});
}
}
Take a look on boost documentation on async_read, the function call always returns immediately. So your callback won't be processed, to make it work, you need to execute run of the m_io_context object. Take a look on boost documentation example.