提高ASIO超时 [英] boost asio timeout
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/291871/how-to-set-a-timeout-on-blocking-sockets-in-boost-asio\">How就在升压asio的阻止套接字设置超时?
我看了一些条目约超时之前,但我不明白。
I read some of the entries before about the timeout but I don't understand.
我要为连接一个规定的时间。
在连接code如下:
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_socket.close();
m_socket.connect(*endpoint_iterator++, error);
}
}
我也想读超时。
我用的boost :: ASIO :: read_until(m_socket,响应为\\ r \\ n);
为读取头
是有可能组简单的超时?
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.
我所做的是很简单的:
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
}
上面的code工作都在Windows和Linux上和Mac OS上,根据OS_WINDOWS宏。
The code above works both on windows and on Linux and on MAC OS, according to the OS_WINDOWS macro.
这篇关于提高ASIO超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!