Skip to content

Instantly share code, notes, and snippets.

@oliverepper
Created April 25, 2022 10:38
Show Gist options
  • Save oliverepper/6b9937849f6d99bac9cf02dddc7153a3 to your computer and use it in GitHub Desktop.
Save oliverepper/6b9937849f6d99bac9cf02dddc7153a3 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <asio.hpp>
#include <array>
using asio::ip::tcp;
using asio::buffer;
void handle_with_future(tcp::socket& client)
{
std::future<std::size_t> bytes_written = client.async_write_some(buffer("Welcome to my nightmare\n"), asio::use_future);
std::cout << bytes_written.get() << " bytes written" << std::endl;
}
void handle_with_callback(tcp::socket& client)
{
client.async_write_some(buffer("Welcome to callback hell\n"),[](std::error_code ec, std::size_t n){
std::cout << n << " bytes written" << std::endl;
});
}
void listen(tcp::acceptor& acceptor)
{
acceptor.async_accept([&acceptor](std::error_code ec, tcp::socket client){
if (!ec) handle_with_future(client);
listen(acceptor);
});
}
int main() {
asio::io_context ctx;
tcp::acceptor acceptor(ctx, tcp::endpoint(tcp::v4(), 1989));
listen(acceptor);
std::cout << std::this_thread::get_id() << std::endl;
ctx.run();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment