简体   繁体   中英

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!

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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM