2012-05-01 32 views
1

我在看的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 :: 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)); 

}

空隙handle_read(常量升压::系统:: 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(); 
} 

}

回答

2

为什么handle_read start_read再打电话来?

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

定时器到期时会发生什么?我看不到提供给定时器的回调例程。

的代码是对源文件的顶部:

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

check_deadline()功能将关闭套接字,如果期限已过。