Boost C++ 库

…是世界上最受尊敬、设计最精良的 C++ 库项目之一。 Herb SutterAndrei AlexandrescuC++ Coding Standards

async_connect (4/4 重载) - Boost C++ 函数库
PrevUpHomeNext

通过尝试序列中的每个终结点来异步建立套接字连接。

template<
    typename Protocol,
    typename Executor,
    typename Iterator,
    typename ConnectCondition,
    typename IteratorConnectToken = default_completion_token_t<Executor>>
DEDUCED async_connect(
    basic_socket< Protocol, Executor > & s,
    Iterator begin,
    Iterator end,
    ConnectCondition connect_condition,
    IteratorConnectToken && token = default_completion_token_t< Executor >(),
    constraint_t< is_connect_condition< ConnectCondition, Iterator >::value >  = 0);

此函数尝试将套接字连接到序列中的一个终结点。它通过反复调用套接字的 async_connect 成员函数来实现,序列中的每个终结点调用一次,直到成功建立连接。它是一个 异步操作 的发起函数,并且始终立即返回。

参数

s

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

begin

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

end

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

connect_condition

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

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

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

标记

将用于生成完成处理程序的 完成令牌,该处理程序将在连接完成时调用。潜在的完成令牌包括 use_futureuse_awaitableyield_context,或者具有正确完成签名的函数对象。完成处理程序的函数签名必须是

void handler(
  // Result of operation. if the sequence is empty, set to
  // boost::asio::error::not_found. Otherwise, contains the
  // error from the last connection attempt.
  const boost::system::error_code& error,

  // On success, an iterator denoting the successfully
  // connected endpoint. Otherwise, the end iterator.
  Iterator iterator
);

无论异步操作是立即完成还是不立即完成,都不会在此函数内部调用完成处理程序。对于立即完成,处理程序的调用将以等同于使用 async_immediate 的方式执行。

完成签名
void(boost::system::error_code, Iterator)
示例

以下连接条件函数对象可用于输出有关单个连接尝试的信息

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);

// ...

r.async_resolve(q, resolve_handler);

// ...

void resolve_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  if (!ec)
  {
    tcp::resolver::iterator end;
    boost::asio::async_connect(s, i, end,
        my_connect_condition(),
        connect_handler);
  }
}

// ...

void connect_handler(
    const boost::system::error_code& ec,
    tcp::resolver::iterator i)
{
  if (ec)
  {
    // An error occurred.
  }
  else
  {
    std::cout << "Connected to: " << i->endpoint() << std::endl;
  }
}
按操作取消

此异步操作支持以下 cancellation_type 值的取消

  • cancellation_type::terminal
  • cancellation_type::partial

如果套接字的 async_connect 操作也支持它们。


PrevUpHomeNext