2011-11-04 580 views
0

我們可以做時間上讀出插座,這樣somethiong:如何使用boost :: asio :: read_some實現超時?

#include <boost/asio.hpp> 
#include <boost/optional.hpp> 

//... 

void http_request::set_result(boost::optional<boost::system::error_code>* a, boost::system::error_code b) 
{ 
    a->reset(b); 
} 
template <typename MutableBufferSequence> 
void read_with_timeout(boost::asio::ip::tcp::socket& sock, 
    const MutableBufferSequence& buffers) 
{ 
    boost::optional<boost::system::error_code> timer_result; 
    boost::asio::deadline_timer timer(sock.io_service()); 
    timer.expires_from_now(seconds(1)); 
    timer.async_wait(boost::bind(set_result, &timer_result, _1)); 
    boost::optional<boost::system::error_code> read_result; 
    async_read(sock, buffers, 
     boost::bind(set_result, &read_result, _1)); 

    sock.io_service().reset(); 
    while (sock.io_service().run_one()) 
    { 
     if (read_result) 
      timer.cancel(); 
     else if (timer_result) 
      sock.cancel(); 
    } 
    if (*read_result) 
     throw std::system_error(*read_result); 
} 

如圖所示here。我想知道是否有可能以及如何在這樣的fashon中實現超時的read_some(我們在哪裏跟蹤時間的第一個符號)?還是有可能使用定時器使用reead_some_unteel

+0

這是我不清楚你問什麼問題的參數。 –

回答

2

我想你可以使用大部分相同的代碼,只需用socket替換async_read即可。 async_read_some和調整您傳遞作爲ReadHandler爲async_read_some

#include <boost/asio.hpp> 
#include <boost/optional.hpp> 

//... 

void http_request::set_result(boost::optional<boost::system::error_code>* a, 
           boost::system::error_code b) 
{ 
    a->reset(b); 
} 
void http_request::set_readsome_result(boost::optional<boost::system::error_code>* oa, 
     boost::optional<std::size_t>* os, 
     boost::system::error_code a, std::size_t b) 
{ 
    oa->reset(a); 
    ob->reset(b); 
} 

// Returns true if successful - false if a timeout occurs 
template <typename MutableBufferSequence> 
bool read_with_timeout(boost::asio::ip::tcp::socket& sock, 
    const MutableBufferSequence& buffers, std::size_t& amount_read) 
{ 
    boost::optional<boost::system::error_code> timer_result; 
    boost::asio::deadline_timer timer(sock.io_service()); 
    timer.expires_from_now(seconds(1)); 
    timer.async_wait(boost::bind(set_result, &timer_result, _1)); 

    boost::optional<boost::system::error_code> read_error_result; 
    boost::optional<std::size_t> read_size_result; 
    sock.async_read_some(buffers, 
     boost::bind(set_result, &read_result, &read_size_result, _1, _2)); 

    sock.io_service().reset(); 
    while (sock.io_service().run_one()) 
    { 
     if (read_result) 
      timer.cancel(); 
     else if (timer_result) 
      sock.cancel(); 
    } 
    if (timer_result) 
     return false; 
    amount_read = *read_size_result; 
    if (*read_error_result) 
     throw std::system_error(*read_result); 
    return true; 

} 
相關問題