I recently saw a bit of code that looked like this (with sock being a socket object of course):
sock.shutdown(socket.SHUT_RDWR)
sock.close()
What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.
there are some flavours of shutdown: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.shutdown.aspx. *nix is similar.
Shutdown(1) , forces the socket no to send any more data
This is usefull in
1- Buffer flushing
2- Strange error detection
3- Safe guarding
Let me explain more , when you send a data from A to B , it's not guaranteed to be sent to B , it's only guaranteed to be sent to the A os buffer , which in turn sends it to the B os buffer
So by calling shutdown(1) on A , you flush A's buffer and an error is raised if the buffer is not empty ie: data has not been sent to the peer yet
Howoever this is irrevesable , so you can do that after you completely sent all your data and you want to be sure that it's atleast at the peer os buffer
Explanation of shutdown and close: Graceful shutdown (msdn)
Shutdown (in your case) indicates to the other end of the connection there is no further intention to read from or write to the socket. Then close frees up any memory associated with the socket.
Omitting shutdown may cause the socket to linger in the OSs stack until the connection has been closed gracefully.
IMO the names 'shutdown' and 'close' are misleading, 'close' and 'destroy' would emphasise their differences.
Here's one explanation:
it's mentioned right in the Socket Programming HOWTO (py2/py3)
Isn't this code above wrong?
The close call directly after the shutdown call might make the kernel discard all outgoing buffers anyway.
According to http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable one needs to wait between the shutdown and the close until read returns 0.