我的程序总是使用平台相关的同步接收,它会阻塞执行直到超时或接收事件,例如:
recv(buf, size, timeout);
现在我想用 boost 替换这段代码以使其跨平台。我找到了解决方案,但我认为它非常难看(与单个函数调用相比)。我写了这个:
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;
}
你能告诉我,我做对了吗?有没有更简单的方法来做到这一点?