Sockets – Properly close a TCP socket

socketstcp

What is the recommended way to "gracefully" close a TCP socket?

I've learned that close()ing before read()ing all the remaining data in my host buffer can cause problems for the remote host (he could lose all the data in his receive buffer that has been acked, but not yet been read by his application). Is that correct?

What would be a good approach to avoid that situation? Is there some way to tell the API that I don't really care about data being lost due to my ignoring any remaining buffered data and closing the socket?

Or do I have to consider the problem at the application protocol level and use some kind of implicit or explicit "end of transmission" signal to let the other party know that it's safe to close a socket for reading?

Best Answer

1) Call shutdown to indicate that you will not write any more data to the socket.

2) Continue to read from the socket until you get either an error or the connection is closed.

3) Now close the socket.

If you don't do this, you may wind up closing the connection while there's still data to be read. This will result in an ungraceful close.