0
votes

I am using boost::asio::io_service to manage some asynchronous TCP communication. The asio version is boost::asio 1.46. I want to make the client reconnect to the server when the server goes down.

Code follows:

tot_client::tot_client(boost::asio::io_service& io_service,
                   tcp::resolver::iterator endpoint_iterator)
: io_service_(io_service),
socket_(io_service)
{
    boost::shared_ptr<tcp::socket> ptr_temp(new tcp::socket(io_service));
    socket_ptr =ptr_temp;
    socket_ptr->async_connect(tcp::endpoint(boost::asio::ip::address_v4::loopback(),2012),
                              boost::bind(&tot_client::handle_connect, this,
                                          boost::asio::placeholders::error));


   } 

if the server is down, my client checks if the socket is open. If the socket isn't open, it then tries to reconnect to the server:

if(socket_ptr.use_count()&&socket_ptr->is_open())

{
   //...
} else 
{
    reconnect ();
}

The reconnect code is here:

void tot_client::reconnect()
{
    try
    {
        std::cout<<" socket_ptr.reset(new tcp::socket(io_service_) ); "<<endl;
        socket_ptr.reset(new tcp::socket(io_service_) );
        //socket_ptr->connect(tcp::endpoint(boost::asio::ip::address_v4::loopback(),2012));
        socket_ptr->async_connect(tcp::endpoint(boost::asio::ip::address_v4::loopback(),2012),
                              boost::bind(&tot_client::handle_connect, this,
                                          boost::asio::placeholders::error));
    }
    catch (std::exception& e )
    {
        std::cerr<<e.what()<<endl;
    }

}

The socket async_connect doesn't work! If I directly use the connect method, the server can receive the socket, but the io_service in the client doesn't work anyway.

Can someone tell me the right way to reconnect to the server? Thanks a lot!

1

1 Answers

0
votes

Are you sure io_service is still running?

if io_service stopped working after it ran out of work, you need to call

io_service.reset();
io_service.run();