c++ - 截止时间计时器到期,现在怎么办?

标签 c++ boost-asio

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

这是我真正难以理解的地方:

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

void start_read()
{ // Set a deadline for the read operation. deadline_.expires_from_now(boost::posix_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)
{ if (stopped_) return;

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

}

最佳答案

Why does handle_read call back start_read again?

如果没有,客户端只会读取套接字一次,然后再也不会读取。因此,在成功读取后,客户端希望再次尝试读取。这有助于永久读取套接字。

What happens when the timer expires? I see no callback routine provided to the timer.

代码在源文件的顶部:

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

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

关于c++ - 截止时间计时器到期,现在怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10401662/

相关文章:

c++ - boost asio async_tcp_echo_server 示例

c++ - Qt 插槽和信号 : no matching function in MainWindow

c++ - 在 OS X 上构建 Qt QIBASE 驱动程序

c++ - boost::asio async_accept 拒绝连接

android - Asio 或 Boost.Asio 可以在 iPhone 或 Android 上运行吗?

sockets - Boost.Asio 的 async_read_some 会是整个消息吗?

c++ - 来自 boost Asio deadline_timer 的多个 async_wait

c++ - 文字效果 GDI+

c++ - 指向外部类 C++

c++ - 如何使用 Google Test 隐藏行号