I have a server application that uses boost::asio’s asynchronous read/write functions to communicate with connecting clients (until they disconnect on their side).
So far everything is good and fine but I would like to implement some kind of timed method where the server sends a packet by himself after a certain amount of time has passed.
I mainly followed the tutorials/examples on the boost::asio website so my program basically has the same structure as the given examples.
I tried to implement this feature by creating an asio::deadline timer object and passing it to the io_service object that I already “invoked” by calling io_service.run() like this:
asio::deadline_timer t(*io, posix_time::seconds(200));
t.async_wait(boost::bind(&connection::handle_timed,
this, boost::asio::placeholders::error));
And the handle_timed handler looks like this:
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));
}
However the problem I have is that the deadline_timer doesn’t wait the given time, he almost immediately goes into the handler function and wants to send the packet.
It’s like he processes that asynchronous operations as soon as he gets to it and thats certainly not what I want to have.
Could it be that I can’t add new “objects” to an io_service object after it was being invoked with io_service.run()? Or maybe I have to specifically include it in the work queue of the io_service object afterwards?
Also I’m having trouble understanding how I can implement this without getting mixed up with the normal message traffic that I have.
You can add work to an
io_serviceat any time. You should check for errors in yourasync_wait()callback, it looks to me like yourdeadline_timergoes out of scopeYou should make it a member of your
connectionclass just likesocket_. Alternatively, useboost::enable_shared_from_thisand keep a copy in your completion handlers:and your completion handler