我正在查看 http://www.boost.org/doc/libs/1_44_0/doc/html/boost_asio/example/timeouts/async_tcp_client.cpp 中的 asio 示例
这是我真正难以理解的地方:
- 为什么 handle_read 会再次回调 start_read?
- 计时器到期时会发生什么?我看到没有提供给计时器的回调例程。
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/