【发布时间】:2017-08-10 15:08:22
【问题描述】:
我正在尝试为 boost 套接字实现 ConnectWithTimeout 函数。所以我使用了我找到的here 的一个例子。这在第一次尝试时效果很好,但是 io_service.run_one() 会立即返回并出现超时或取消错误。
这是我的代码
using NetStatus = boost::system::error_code;
NetStatus handleWait(const NetStatus& error)
{
return boost::asio::error::timed_out;
}
NetStatus handleConnect(const NetStatus& error)
{
// The async_connect() function automatically opens the socket at the start
// of the asynchronous operation. If the socket is closed at this time then
// the timeout handler must have run first.
if (!m_socket.is_open())
return boost::asio::error::timed_out;
// Otherwise, a connection has been established. Update the timer state
// so that the timeout handler does not close the socket.
m_connectionTimeoutTimer.cancel();
return error;
}
void connectWithTimeout(boost::asio::ip::tcp::endpoint& endpoint, NetStatus& e)
{
// Stop last time's waiting objects
m_socket.cancel()
m_connectionTimeoutTimer.cancel();
m_ioService.stop();
m_ioService.reset();
// Set-up new objects to wait
m_connectionTimeoutTimer.expires_from_now(boost::posix_time::seconds(5));
m_connectionTimeoutTimer.async_wait([this, &e](const NetStatus& error) { e = handleWait(error); } );
m_socket.async_connect(endpoint, [this, &e](const NetStatus& error) { e = handleConnect(error); } );
// Block until one of them is done
m_ioService.run_one(e);
}
boost::asio::ip::tcp::socket m_socket;
boost::asio::deadline_timer m_connectionTimeoutTimer;
我在循环中运行时看到的结果是: 超时(按预期在 5 秒后) 取消(立即) 超时(立即) 取消(立即) 超时(立即) 取消(立即) 超时(立即) ...
谁能帮忙找出我做错了什么?
【问题讨论】:
-
我不明白你为什么在
connectWithTimeout()函数中调用m_ioService.stop();和m_ioService.reset(); -
我试图让 io_service 停止从上一次运行中弹出事件,所以我通过运行 reset 和 stop 确保没有以前的处理程序在等待。