Boost C++ Libraries

PrevUpHomeNext

Function template tcp

boost::taar::server::tcp — Coroutine that binds, listens, and accepts TCP connections.

Synopsis

// In header: <boost/taar/server/tcp.hpp>


template<typename SessionHandler> 
  awaitable< void > 
  tcp(boost::asio::any_io_executor connection_executor, std::string bind_host, 
      std::string bind_port, SessionHandler && session_handler, 
      cancellation_signals & signals, 
      std::function< void(boost::asio::ip::tcp::endpoint const &)> local_endpoint_handler = nullptr);

Description

Spawn one instance of this coroutine per listen endpoint. It resolves bind_host / bind_port, opens an acceptor with SO_REUSEADDR, starts listening on max_listen_connections, and then loops accepting connections until cancellation is requested through signals.

Each accepted socket is forwarded to session_handler on its own strand, made from connection_executor, so the io_context may be run by several threads and connections are served in parallel. The handler is responsible for the full lifetime of the connection, typically by invoking a session::http instance.

The acceptor and every connection register themselves with signals, and signals.emit() may be called from any thread. A cancellation slot bound to this coroutine by its spawner also stops it (safely, through the acceptor's strand), though it is no longer needed.

Parameters:

connection_executor

The executor every connection strand is made from: normally the io_context (or thread pool) executor itself. The acceptor runs on a strand of the executor this coroutine is spawned on, independently.

bind_host

Host or address to bind. "0.0.0.0" and "::" accept on all interfaces.

bind_port

Port string. "0" asks the OS to pick a port; use local_endpoint_handler to learn the chosen port.

session_handler

A callable invoked as session_handler(socket, signals), where socket is a boost::asio::ip::tcp::socket already on the connection strand, and returning awaitable<void>. Usually a session::http instance by reference.

signals

Cancellation pool. The same pool is shared with spawned sessions so a single cancellation_signals::emit shuts the server down.

local_endpoint_handler

Optional callback invoked with the resolved local endpoint after bind().

Throws:

boost::taar::exception carrying the system error code if name resolution, binding or listening fails.

PrevUpHomeNext