2013-01-13 52 views
1

我有一个服务器应用程序,使用boost :: asio的异步读/写功能与连接客户端进行通信(直到他们断开连接)。boost :: asio如何实现定时数据包发送功能?

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

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

我试图通过调用io_service.run()这样通过创建ASIO ::期限定时器对象并将它传递给,我已经“援引”的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.run()调用io_service对象后,我不能添加新的“对象”?或者,也许我必须特别将它包含在io_service对象的工作队列中?

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

+0

是否使用TCP套接字

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)); 

和你完成处理:或者,使用boost::enable_shared_from_this并保留一份副本在你完成处理?如果是这样,你可以考虑[保持活力](http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html)。 –

+0

是的,我正在使用TCP套接字,但我宁愿发送数据包以及我通常发送的其他数据包,因为我想在其中放入一些数据。 – user1175111

回答

1

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

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)); 
} 
+0

感谢您的快速回答,将deadline_timer对象添加到类中就有窍门。 – user1175111

+0

@用户没问题,祝你好运。如果您遇到困难,请提出其他问题。 –

相关问题