Jeff here again from the Windows SDK Team.
Recently, I had a case where the customer required use of the TCP Linger option to reset a connection when it was closed.
I was able to get it to work in native Winsock with no problem, but getting the reset to be sent in .NET was rather elusive. I spendmuch more of my time working in native rather than managed code, so maybe this is more obvious to others than it was to myself.
Here is the Linger option I wanted to set:
LingerOption lingerOption = new LingerOption(true, 0);
// Set the Linger Option on the TCPClient.Client client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
The sample from MSDN for TcpListener creates a server that accepts client connections. The sample closes the client with this code:
// Close connection client.Close();
However, this won’t invoke the Linger settings and reset the connection. To do that we need to close the client connection in the client thisway:
// Close connection AND RST the connection client.Client.Close();
Closing the connection this way sends a RST to the client and lets them know that theconnection has been closed and no further data will be accepted. Otherwise, theclient wouldn’t know it was closed until they tried to send data to it again.