Boost :: asio socket - how to disconnect them cleanly?

I am using asynchronous boost sockets for my server application. I created a disconnect () function that calls boost close () and then deletes the socket (delete statement). And this is normal when a function is called from one of the asynchronous ones. handlers, but when I call it from inside my main code base, the whole application crashes on one of the async handlers. How to close a socket beautifully in boost?

+4
source share
2 answers

Make sure that the object is alive as long as there are handlers that can use it.

Probably one of the handlers that uses this socket is called after you call close (since it reports an error to the handler), and then refers to the dead pointer ...

Typically, lifetime processing can be easily done with boost::shared_ptr and boost::enable_shared_from_this and passed in handlers. See Numerous examples with Boost.Asio.

Once you become familiar with this technique, the question you ask will look trivial for you.

+2
source

You also want to see the shutdown method on the socket. This will not solve your emergency application. Artyom already explained the reason for this, but he is nonetheless interesting. If you close the socket without causing a shutdown, this may result in sending an RST instead of a competent FIN handshake.

+1
source

All Articles