截止日期计时器过期,现在怎么办

deadline timer expires, now what?

本文关键字:怎么办 过期 日期 计时器      更新时间:2023-10-16

我正在查看 asio 示例中的 http://www.boost.org/doc/libs/1_44_0/doc/html/boost_asio/example/timeouts/async_tcp_client.cpp

以下是我真正难以理解的内容:

  1. 为什么handle_read又回start_read?
  2. 计时器过期时会发生什么?我没有看到向计时器提供回调例程。

无效 start_read()
{ 设置读取操作的截止时间。 deadline_.expires_from_now(boost::p osix_time::seconds(30));

// Start an asynchronous operation to read a newline-delimited message.
boost::asio::async_read_until(socket_, input_buffer_, 'n',
    boost::bind(&client::handle_read, this, _1));   

}

void handle_read(const boost::system::error_code& ec)
{ 如果 (stopped_) 返回;

if (!ec)
{
  // Extract the newline-delimited message from the buffer.
  std::string line;
  std::istream is(&input_buffer_);
  std::getline(is, line);
  // Empty messages are heartbeats and so ignored.
  if (!line.empty())
  {
    std::cout << "Received: " << line << "n";
  }
  start_read();
}
else
{
  std::cout << "Error on receive: " << ec.message() << "n";
  stop();
}   

}

为什么handle_read又回start_read?

否则,客户端将只读取一次套接字,然后再也不会读取。因此,在成功读取时,客户端希望再次尝试读取。这使得套接字的永久读取。

计时器过期时会发生什么?我没有看到向计时器提供回调例程。

代码位于源文件的顶部:

deadline_.async_wait(boost::bind(&client::check_deadline, this));

如果截止日期已过,check_deadline()函数将关闭套接字。