我的程序总是习惯依赖于平台的同步接收,阻碍执行,直到超时或接收事件,喜欢的东西:async_read_some效仿syncronous超时收到
recv(buf, size, timeout);
现在我要替换此代码促使它跨平台。我找到了解决方案,但我认为这很难看(与单一函数调用相比)。我写了这样的:
void IPV4_HOST::recv_timer_handler(const boost::system::error_code & e)
{
if (e.value() == boost::system::errc::success) {
f_recv_timeout = true;
asio_socket.cancel();
}
}
void IPV4_HOST::recv_handler(const boost::system::error_code & , size_t bytes)
{
recv_timer.cancel();
bytes_received = bytes;
}
int IPV4_HOST::receive(void * buf, size_t buf_size, TIME::INTERVAL timeout)
{
f_recv_timeout = false;
bytes_received = 0;
recv_timer.expires_from_now(timeout.get_boost_milli());
recv_timer.async_wait(boost::bind(&IPV4_HOST::recv_timer_handler, this, boost::asio::placeholders::error));
asio_socket.async_read_some(boost::asio::buffer(buf, buf_size),
boost::bind(&IPV4_HOST::recv_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
io_service.run();
if (f_recv_timeout)
throw IO::TimeoutReceiveException();
return bytes_received;
}
请问你能否告诉我,我是对的还是不对?有没有简单的方法来做到这一点?
请参阅库作者的以下答案:http://boost.2283326.n4.nabble.com/asio-setting-a-timeout-on-blocking-write-s-read-s-tt2624802.html# a2624803 – 2013-03-01 13:01:27
这几乎等于我所做的,但无论如何谢谢 – 2013-03-01 13:51:47