我已经实现了一个非常标准的阻塞 api 仿真,它具有 boost::asio 的超时。这是我的主要周期:
io_service io_svc;
tcp::endpoint endpoint(tcp::v4(), m_port);
tcp::acceptor acceptor(io_svc, endpoint);
accept_helper acc_hlpr(acceptor, 5000);
while (m_bStop == false)
{
tcp::socket socket(io_svc);
if (acc_hlpr.accept(socket))
{
// do stuff
socket.close();
}
}
这是助手类
class accept_helper
{
public:
accept_helper (tcp::acceptor &acc, size_t msTO) : m_timer(acc.get_io_service()), m_acceptor(acc), m_msTO(msTO) { }
bool accept (tcp::socket &socket)
{
m_bTimeout = false;
m_bAccept = false;
m_timer.expires_from_now(boost::posix_time::milliseconds(m_msTO));
m_timer.async_wait(boost::bind(&accept_helper::handle_timeout, this, boost::asio::placeholders::error));
m_acceptor.async_accept(socket, boost::bind(&accept_helper::handle_accept, this));
m_timer.get_io_service().run_one();
m_timer.get_io_service().reset();
if (m_bAccept)
{
m_timer.cancel();
return true;
}
else if (m_bTimeout)
{
// BOOST_ASIO_ENABLE_CANCELIO is defined
boost::system::error_code ec;
m_acceptor.cancel(ec);
}
return false;
}
private:
void handle_accept (void)
{
boost::mutex::scoped_lock lock(m_mutex);
m_bAccept = true;
}
void handle_timeout(const boost::system::error_code & error)
{
if (!error)
{
boost::mutex::scoped_lock lock(m_mutex);
m_bTimeout = true;
}
}
private:
boost::asio::deadline_timer m_timer;
boost::asio::ip::tcp::acceptor &m_acceptor;
boost::mutex m_mutex;
size_t m_msTO;
bool m_bTimeout;
bool m_bAccept;
};
问题是计时器仅在第一次迭代时等待。在其他人 run_one 方法只是立即返回并且没有设置标志。我试图让计时器本地化,但这没有帮助。如何让计时器每次都等待?
固定版本
bool accept (tcp::socket &socket)
{
m_bTimeout = false;
m_bAccept = false;
m_timer.expires_from_now(boost::posix_time::milliseconds(m_msTO));
m_timer.async_wait(boost::bind(&accept_helper::handle_timeout, this, boost::asio::placeholders::error));
m_acceptor.async_accept(socket, boost::bind(&accept_helper::handle_accept, this, boost::asio::placeholders::error));
m_timer.get_io_service().reset();
m_timer.get_io_service().run_one();
if (m_bAccept)
{
m_timer.cancel();
}
else if (m_bTimeout)
{
boost::system::error_code ec;
m_acceptor.cancel(ec);
}
while (m_timer.get_io_service().run_one());
return m_bAccept;
}
private:
void handle_accept (const boost::system::error_code & error)
{
if (!error)
{
boost::mutex::scoped_lock lock(m_mutex);
m_bAccept = true;
}
}
void handle_timeout(const boost::system::error_code & error)
{
if (!error)
{
boost::mutex::scoped_lock lock(m_mutex);
m_bTimeout = true;
}
}