Boost::asio如何实现定时数据包发送功能



我有一个服务器应用程序,它使用boost::asio的异步读/写函数与连接的客户端进行通信(直到它们断开连接)。

到目前为止一切都很好,但我想实现某种定时方法,其中服务器在一定时间后自行发送数据包。

我主要遵循boost::asio网站上的教程/示例,所以我的程序基本上与给出的示例具有相同的结构。

我尝试通过创建asio::deadline计时器对象并将其传递给我已经通过调用io_service.run()"调用"的io_service对象来实现此功能,如下所示:

asio::deadline_timer t(*io, posix_time::seconds(200));
t.async_wait(boost::bind(&connection::handle_timed, 
                this, boost::asio::placeholders::error));

handle_timed处理程序是这样的:

void connection::handle_timed(const system::error_code& error)
{
    //Ping packet is created here and gets stored in send_data
    async_write(socket_, asio::buffer(send_data, send_length), 
                boost::bind(&connection::handle_write, this, boost::asio::placeholders::error));
}

然而,我的问题是,deadline_timer没有等待给定的时间,他几乎立即进入处理程序函数,想要发送数据包。

就像他一到达异步操作就处理它,这当然不是我想要的。

可能是我不能添加新的"对象"到io_service对象后,它被io_service.run()调用?或者我可能必须在io_service对象的工作队列中特别包含它?

另外,我很难理解如何实现这一点,而不会与我拥有的正常消息流量混淆。

您可以随时向io_service添加工作。你应该检查async_wait()回调中的错误,在我看来,你的deadline_timer超出了作用域

asio::deadline_timer t(*io, posix_time::seconds(200));
t.async_wait(boost::bind(&connection::handle_timed, 
                this, boost::asio::placeholders::error));
...
// t goes out of scope here

您应该使它成为connection类的成员,就像socket_一样。或者,使用boost::enable_shared_from_this并在完成处理程序中保留一个副本:

const boost::shared_ptr<asio::deadline_timer> t(new asio::deadline_timer(*io, posix_time::seconds(200)));
t.async_wait(boost::bind(&connection::handle_timed, 
                this, boost::asio::placeholders, t));

和你的完成处理程序

void connection::handle_timed(
    const system::error_code& error,
    const boost::shared_ptr<asio::deadline_timer>& timer
    )
{
    //Ping packet is created here and gets stored in send_data
    async_write(socket_, asio::buffer(send_data, send_length), 
                boost::bind(&connection::handle_write, this, boost::asio::placeholders::error));
}

最新更新