boost::corosio::connect

Asynchronously connect a socket by trying each endpoint in a range.

Synopsis

template<
    class Socket,
    std::ranges::input_range Range>
requires std::convertible_to<
        std::ranges::range_reference_t<Range>,
        typename Socket::endpoint_type>
capy::task<capy::io_result<Socket::endpoint_type>>
connect(
    Socket& s,
    Range endpoints);

Description

Each candidate is tried in order. Before each attempt the socket is closed (so the next connect auto‐opens with the candidate's address family). On first successful connect, the operation completes with the connected endpoint.

Cancellation

Supports cancellation via the affine awaitable protocol. If a per‐endpoint connect completes with capy::cond::canceled the operation completes immediately with that error and does not try further endpoints.

The socket is closed and re‐opened before each attempt, so any socket options set by the caller (e.g. no_delay, reuse_address) are lost. Apply options after this operation completes.

Example

resolver r(ioc);
auto [rec, results] = co_await r.resolve("www.boost.org", "80");
if (rec) co_return;
tcp_socket s(ioc);
auto [cec, ep] = co_await corosio::connect(s, results);

Exceptions

Name

Thrown on

std::system_error

if auto‐opening the socket fails during an attempt (inherits the contract of Socket::connect).

Return Value

An awaitable completing with capy::io_result<typename Socket::endpoint_type>: ‐ on success: default error_code and the connected endpoint; ‐ on failure of all attempts: the error from the last attempt and a default‐constructed endpoint; ‐ on empty range: std::errc::no_such_device_or_address and a default‐constructed endpoint.

Parameters

Name

Description

s

The socket to connect. Must have a connect(endpoint) member returning an awaitable, plus close() and is_open(). If the socket is already open, it will be closed before the first attempt.

endpoints

A range of candidate endpoints. Taken by value so temporaries (e.g. resolver_results returned from resolver::resolve) remain alive for the coroutine's lifetime. Because the range is owned by the coroutine, passing an lvalue copies it; since resolver_results is a std::vector<resolver_entry>, that is a deep copy of every entry. Pass an rvalue (std::move(results)) or use the iterator overload (connect(s, results.begin(), results.end())) to avoid the copy.

Created with MrDocs