Visual C++ Network: How do I terminate a TCP connection?
Q: How do I terminate a TCP connection?
A: Closing a connection can be trickier to handle. The trickier part comes when you decide to handle the data properly at the time of closing the connection. If you don't care about the data that is being sent or received at the time of closing, then terminating a connection becomes easy. Just call 'closesocket()' and your connection gets disconnected. Any further reference to the socket, like 'send()' or 'recv()' fails with an error.
When you call 'closesocket()' your connection is not reset or closed immediately, though this is what it seems to do. But actually what happens in the background is any unsent data (in the buffer) is send before closing the socket. But any data that is on the way to you from the peer or is still in the buffer, is lost, since by then we would loose the actual socket descriptor.
One technique often used to minimize the problem at the time of closing, is to use the 'shutdown()' call before calling 'closesocket()'. The advantage using 'shutdown()' is, it never closes the actual socket, but only disables 'recv()' or 'send()' or both. Hence, when we disable 'send()', the peer is notified that we don't intend to send data anymore. A common usage of shutdown sequence is as follows:
Once you finish sending all the data, call 'shutdown()' with the 'how' parameter as 'SD_SEND'.
On the peer side, call 'recv()' in a loop till you get 0 as the return value.
On the peer side, call 'shutdown()' with 'SD_SEND' after you send all the data.
Your application should loop on 'recv()' till you get 0.
On the peer side you can close the socket right after the third step. You can also directly call the 'closesocket()' instead of the third step, after sending data if any.
PS: It is assumed that the linger option 'SO_LINGER' is not set using the 'setsockopt()'. By default this is not set. If this is set, the way the application behaves at the time of calling 'closesocket()' will change. More information can be found here.
Last edited by Andreas Masur; November 13th, 2005 at 07:31 AM.