Boost C++ 库

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

connect(8 个重载中的第 7 个) - Boost C++ 函数库
PrevUpHomeNext

通过尝试序列中的每个端点来建立套接字连接。

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 成员函数来实现,序列中的每个端点调用一次,直到成功建立连接为止。

参数

s

要连接的套接字。如果套接字已打开,它将被关闭。

begin

指向终结点序列开头的迭代器。

end

指向终结点序列末尾的迭代器。

connect_condition

一个函数对象,在每次连接尝试之前调用。函数对象的签名必须是

bool connect_condition(
   const boost::system::error_code& ec,
   const typename Protocol::endpoint& next);

ec 参数包含最近一次 connect 操作的结果。在第一次连接尝试之前,ec 始终设置为表示成功。next 参数是要尝试的下一个端点。如果应尝试下一个端点,则函数对象应返回 true,如果应跳过,则返回 false。

返回值

一个迭代器,表示成功连接的端点。

异常

boost::system::system_error

失败时抛出。如果序列为空,则关联的 error_codeboost::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;

PrevUpHomeNext