boost :: asio如何实现定时数据包发送function?

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

到目前为止,一切都很好,但我想实现某种定时的方法,服务器在经过一段时间后自己发送一个包。

我主要关注boost :: asio网站上的教程/例子,所以我的程序基本上和给出的例子具有相同的结构。

我试图通过创build一个asio :: deadline计时器对象并通过调用io_service.run()将它传递给我已经“调用”的io_service对象来实现此function:

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不等待给定的时间,他几乎立即进入处理函数,并希望发送数据包。

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

难道是因为io_service.run()被调用后,我不能添加新的“对象”到io_service对象吗? 或者,也许我必须特别将其包含在io_service对象的工作队列中?

此外,我无法理解如何实现这一点,而不会混淆正常的消息stream量。

您可以随时将工作添加到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)); }