I am looking at the asio example in http://www.boost.org/doc/libs/1_44_0/doc/html/boost_asio/example/timeouts/async_tcp_client.cpp
Here’s what I am having real trouble to understand:
- Why does handle_read call back start_read again?
- What happens when the timer expires? I see no callback routine provided to the timer.
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(); }}
If it didn’t, the client would only ever read the socket once and then never again. So on a successful read, the client wants to attempt a read again. That makes for perpetual reading of the socket.
The code is towards the top of the source file:
The
check_deadline()function will close the socket if the deadline has passed.