c++multithreadingboostboost-asiodisconnect

Cancel connection is boost::asio


From the standard SSL client example. Say I call this function.

    boost::asio::async_connect(socket_.lowest_layer(), endpoint_iterator,
                               boost::bind(&SSLClient::handle_connect, this,
                                           boost::asio::placeholders::error));

But then the function is called, and the program is connecting. I would like to cancel my request and stop the connection! How can I do that?

Special case: Say I have those objects in a thread. Is there a way to do it in this case?

Now if I try to do this, the program simply doesn't respond. I don't see a way to force it to stop!


Solution

  • There are several ways to achieve what you want ¹.

    1. You could hard-stop the service (service.stop()). But this leaves you no control over all running operations. It's the "nuclear" approach, so to say.

    2. The controlled way would be to call cancel()

      Cancel all asynchronous operations associated with the socket.

      socket_.cancel()
      

    Now, you have the additional task of maintaining the lifetime of your connection object (presumably the this in your bound completion handler). A very common pattern to use is to make the connection class derive from enable_shared_from_this and bind the completion handler to shared_from_this() instead of just this.

    That way, the shared connection object will automatically "go away" after the last pending async operation has been canceled, and you don't have to worry about leaking connection objects.

    ¹ short of exit, abort, quick_exit etc. :)