c++ tcp client - How do I cleanly reconnect a boost::socket following a disconnect?





2 Answers

For the sake of clarity here is the final approach I used (but this is based on bjlaub's answer, so please give any upvotes to him):

I declared the socket member as a scoped_ptr:

boost::scoped_ptr<boost::asio::ip::tcp::socket> socket;

Then I modified my connect method to be:

bool MyClient::myconnect()
{
    bool isConnected = false;

    // Create new socket (old one is destroyed automatically)
    socket.reset(new boost::asio::ip::tcp::socket(io_service));

    // Attempt connection
    socket->connect(server_endpoint, errorcode);

    if (errorcode)
    {
        cerr << "Connection failed: " << errorcode.message() << endl;
        socket->close();
    }
    else
    {
        isConnected = true;

        // Connected so setup async read for an incoming message.
        startReadMessage();

        // And start the io_service_thread
        io_service_thread = new boost::thread(
            boost::bind(&MyClient::runIOService, this, boost::ref(io_service)));
    }
    return (isConnected)
}

Note: this question was originally asked and answered back in 2010, but if you are now using C++11 or later then std::unique_ptr would normally be a better choice than boost::scoped_ptr

asio tutorial

My client application uses a boost::asio::ip::tcp::socket to connect to a remote server. If the app loses connection to this server (e.g. due to the server crashing or being shutdown) I would like it to attempt a re-connect at regular intervals until it succeeds.

What do I need to do on the client-side to cleanly handle a disconnect, tidy up and then repeatedly attempt reconnects?

Currently the interesting bits of my code look something like this.

I connect like this:

bool MyClient::myconnect()
{
    bool isConnected = false;

    // Attempt connection
    socket.connect(server_endpoint, errorcode);

    if (errorcode)
    {
        cerr << "Connection failed: " << errorcode.message() << endl;
        mydisconnect();
    }
    else
    {
        isConnected = true;

        // Connected so setup async read for an incoming message.
        startReadMessage();

        // And start the io_service_thread
        io_service_thread = new boost::thread(
            boost::bind(&MyClient::runIOService, this, boost::ref(io_service)));
    }
    return (isConnected)
}

Where the runIOServer() method is just:

void MyClient::runIOService(boost::asio::io_service& io_service)
{
    size_t executedCount = io_service.run();
    cout << "io_service: " << executedCount << " handlers executed." << endl;
    io_service.reset();
}

And if any of the async read handlers return an error then they just call this disconnect method:

void MyClient::mydisconnect(void)
{
    boost::system::error_code errorcode;

    if (socket.is_open())
    {
        // Boost documentation recommends calling shutdown first
        // for "graceful" closing of socket.
        socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorcode);
        if (errorcode)
        {
            cerr << "socket.shutdown error: " << errorcode.message() << endl;
        }

        socket.close(errorcode);
        if (errorcode)
        {
            cerr << "socket.close error: " << errorcode.message() << endl;
        }    

        // Notify the observer we have disconnected
        myObserver->disconnected();            
    }

..which attempts to gracefully disconnect and then notifies an observer, which will start calling connect() at five second intervals until it gets reconnected.

Is there anything else I need to do?

Currently this does seem to work. If I kill the server that it is connected to I get the expected "End of file" error at my read handlers and mydisconnect() is called without any issues.

But when it then attempts to re-connect and fails I see it report "socket.shutdown error: Invalid argument". Is this just because I am attempting to shutdown a socket that has no read/writes pending on it? Or is it something more?




I have tried both the close() method and the shutdown method and they are just to tricky for me. Close() can throw an error that you need to catch and is the rude way to do what you want :) and shutdown() seems to be best but on multithreaded software, I find it can be fussy. So the best way is, as Sam said, to let it go out of scope. If the socket is a member of the class you can 1) redesign so that the class uses a 'connection' object to wrap the socket and let it go out of scope or 2) wrap it in a smart pointer and reset the smart pointer. If you using boost, including the shared_ptr is cheap and works like a charm. Never had a socket clean up issue doing it with a shared_ptr. Just my experience.






Related