Search code examples
c#socketshalf-close

Need help writing to a socket after receiving a shutdown on the read side


I am trying to implement an HTTP proxy in C# as part of an overall business application I'm working on, and have run into the following conundrum.

Part of the HTTP standard specifies that the browser may issue a socket shutdown (SocketShutdown.Send), at which point the server will deliver any remaining data to the browser and close its own half of the socket. I am getting the expected behavior on the receiving side of the socket when the browser half-closes its connection, namely Select() indicates that the socket is readable, but reading from the socket using Receive() returns zero bytes. But when I try to write to my side of the socket using Send(), I get a SocketException indicating a WSAECONNRESET. It is as if the Shutdown() by the browser is causing the whole TCP connection to be torn down rather than just the inbound leg.

Does anyone have experience using half-closed sockets in C#, and specifically of writing to a socket that was half-closed by your peer?

No sample code for now, but I will provide some if there isn't anyone who can respond.


Solution

  • You can't tell whether the incoming FIN was caused by a shutdown or a close. In this case it was clearly caused by a close. The correct technique when you get a FIN on an inbound socket A is to shutdown the corresponding outbound socket B for writing, then when you get a FIN on that socket as inbound socket (B), shutdown the corresponding outbound socket A for writing. When you have shutdown both sockets, close them both.