...one of the most highly regarded and expertly designed C++ library projects in the world.
— Herb Sutter and Andrei Alexandrescu, C++ Coding Standards
通过尝试序列中的每个端点来建立套接字连接。
template< typename Protocol, typename Executor, typename Iterator, typename ConnectCondition> Iterator connect( basic_socket< Protocol, Executor > & s, Iterator begin, Iterator end, ConnectCondition connect_condition, constraint_t< is_connect_condition< ConnectCondition, Iterator >::value > = 0);
此函数尝试将套接字连接到序列中的一个端点。它通过重复调用套接字的 connect
成员函数来实现,序列中的每个端点调用一次,直到成功建立连接为止。
要连接的套接字。如果套接字已打开,它将被关闭。
指向终结点序列开头的迭代器。
指向终结点序列末尾的迭代器。
一个函数对象,在每次连接尝试之前调用。函数对象的签名必须是
bool connect_condition( const boost::system::error_code& ec, const typename Protocol::endpoint& next);
参数包含最近一次 connect 操作的结果。在第一次连接尝试之前,ec
始终设置为表示成功。ec
参数是要尝试的下一个端点。如果应尝试下一个端点,则函数对象应返回 true,如果应跳过,则返回 false。next
一个迭代器,表示成功连接的端点。
失败时抛出。如果序列为空,则关联的 error_code
为 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::resolver::results_type e = r.resolve(q); tcp::socket s(my_context); tcp::resolver::results_type::iterator i = boost::asio::connect( s, e.begin(), e.end(), my_connect_condition()); std::cout << "Connected to: " << i->endpoint() << std::endl;