I have written a TCP/IP program, in which the client uses ordinary (non-Boost) socket API; i.e. the server binds and listens, and the client connects. The server uses pthreads to handle several clients at a time.
The program uses OpenSSL to exchange session keys between the client and the server.
Later, I noticed that periodically, I need to perform a “re-key”: After the session is established, I have to schedule a re-key task, in which the client and the server agree upon a new session key.
One option was to create a new thread for each client: The new thread will sleep for a period of time, and then awakens and initiates a re-key. This option is rather expensive, since each client needs to be multi-threaded.
Another option was to use Boost Asio. I regret I wasn’t aware that this valuable library existed; otherwise, I’d coded the program using Boost’s threads and Boost’s sockets.
Anyway, I want to do the job with minimum change. At first, I misunderstood Asio. Using Boost’s Timer 2 example, I wrote something like this:
void rekey(const boost::system::error_code& /*e*/)
{
// do rekey
}
...
void main()
{
//connect to server
// schedule re-key
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::minutes(30));
t.async_wait(rekey);
io.run();
// the rest of job (i.e. sending and receiving messages in a while() loop.)
}
This is clearly wrong, since Boost blocks at io.run(). My first perception was that the asynchronous nature of async_wait will solve the problem, but clearly I misunderstood the Asio model.
I have two solutions in mind:
- Generate a function in which sending and receiving is performed (using ordinary socket API), and add this function to the queue of
ioobject, so thatio.run()works as expected. - Re-write the socket functions using Boost’s asynchronous socket API.
Is there a better solution? In any case, could you please help me figure out how to implement the best solution?
Generally,
io_service::run()(or the other functions that cause events to happen such asio_service::poll(),io_servive::run_one()andio_service::poll_one()) would be run in their own thread.I’m a big proponent of the boost::asio library, as once you are used to coding with it, it is a very elegant and powerful library. However, if you already have a large portion of the application written (and working) I would not suggest rewriting it just to take advantage of boost::asio, especially if you only need some type of asynchronous timer.
Since you stated that each client already has its own thread, I’d suggest using some type of sentinel that you periodically check in that thread to indicate when the re-key was necessary.