开发者

boost asio timeout [duplicate]

开发者 https://www.devze.com 2023-03-06 12:21 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: How to set a timeout on blocking sockets in boost asio?
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

How to set a timeout on blocking sockets in boost asio?

I read some of the entries before about the timeout but I don't understand.

I want a defined timeout for the connection. the connect code looks like:

try{
  boost::asio::ip::tcp::resolver              resolver(m_ioService);
  boost::asio::ip::tcp::resolver::query       query(link.get_host(), link.get_scheme());
  boost::asio::ip::tcp::resolver::iterator    endpoint_iterator = resolver.resolve(query);
  boost::asio::ip::tcp::resolver::iterator    end;
  boost::system::error_code                   error   =   boost::asio::error::host_not_found;

  while (error && endpoint_iterator != end)
   {
    m_sock开发者_运维技巧et.close();
    m_socket.connect(*endpoint_iterator++, error);
   }
}

also I want a read timeout.

I use boost::asio::read_until(m_socket, response, "\r\n"); for read the header.

is it possible to set SIMPLE a timeout?


Fist of all I believe that you should ALWAYS use the async methods since they are better and your design will only benefit from a reactor pattern approach. In the bad case that you're in a hurry and you're kind of prototyping, the sync methods can be useful. In this case I do agree with you that without any timeout support, they cannot be used in the real world.

What I did was very simple:

void HttpClientImpl::configureSocketTimeouts(boost::asio::ip::tcp::socket& socket)
{
#if defined OS_WINDOWS
    int32_t timeout = 15000;
    setsockopt(socket.native(), SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
    setsockopt(socket.native(), SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout, sizeof(timeout));
#else
    struct timeval tv;
    tv.tv_sec  = 15; 
    tv.tv_usec = 0;         
    setsockopt(socket.native(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
    setsockopt(socket.native(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
#endif
}

The code above works both on windows and on Linux and on MAC OS, according to the OS_WINDOWS macro.


Using boost::asio and the sychronous calls like read_until do not allow for easily setting a timeout.

I'd suggest moving to asynchronous calls (like async_read), and combining that with a deadline_timer to accomplish this goal.

0

精彩评论

暂无评论...
验证码 换一张
取 消