Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly close a TCP socket

Tags:

tcp

sockets

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?

like image 362
lxgr Avatar asked Jan 15 '12 20:01

lxgr


1 Answers

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.

like image 111
David Schwartz Avatar answered Oct 18 '22 20:10

David Schwartz