通过尝试序列中的每个端点来建立套接字连接。
template< typename Protocol, typename Executor, typename EndpointSequence, typename ConnectCondition> Protocol::endpoint connect( basic_socket< Protocol, Executor > & s, const EndpointSequence & endpoints, ConnectCondition connect_condition, boost::system::error_code & ec, constraint_t< is_endpoint_sequence< EndpointSequence >::value > = 0, constraint_t< is_connect_condition< ConnectCondition, decltype(declval< const EndpointSequence & >().begin())>::value >= 0);
此函数尝试将套接字连接到一系列终结点中的一个。它通过重复调用套接字的 connect
成员函数来实现,对序列中的每个终结点调用一次,直到成功建立连接。
要连接的套接字。如果套接字已打开,它将被关闭。
一系列端点。
一个函数对象,在每次连接尝试之前调用。函数对象的签名必须是
bool connect_condition( const boost::system::error_code& ec, const typename Protocol::endpoint& next);
ec
参数包含最近一次 connect 操作的结果。在第一次连接尝试之前,ec
始终设置为表示成功。 next
参数是要尝试的下一个终结点。如果应尝试下一个终结点,则函数对象应返回 true,如果应跳过,则返回 false。
设置为指示发生了什么错误(如果有)。如果序列为空,则设置为 boost::asio::error::not_found
。否则,包含最后一次连接尝试的错误。
成功时,返回成功连接的端点。否则,返回默认构造的端点。
以下连接条件函数对象可用于输出有关单个连接尝试的信息
struct my_connect_condition { bool operator()( const boost::system::error_code& ec, const::tcp::endpoint& next) { if (ec) std::cout << "Error: " << ec.message() << std::endl; std::cout << "Trying: " << next << std::endl; return true; } };
它将与 connect
函数一起使用,如下所示:
tcp::resolver r(my_context); tcp::resolver::query q("host", "service"); tcp::socket s(my_context); boost::system::error_code ec; tcp::endpoint e = boost::asio::connect(s, r.resolve(q), my_connect_condition(), ec); if (ec) { // An error occurred. } else { std::cout << "Connected to: " << e << std::endl; }