Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Gracefully Close a Socket from the Server

On the server side, I'm trying to gracefully close a connected socket. I know the proper sequence of events on the Socket should be:

  1. socket Shutdown with the SocketShutdown.Send option

  2. loop/wait until a socket Receive returns with 0 bytes

  3. socket Close

I have a few questions:

  1. what if Socket.Receive never returns (with 0 bytes)? will we be stuck trying to close the socket forever?

  2. whenever i call Close on the server, the Client always receives "an existing connection was forcibly closed by a remote host" exception on their end. how can i have the client notified of this close "gracefully"?

  3. on the server, if I'm using Async Begin/EndReceive calls, whenever I call Close on the socket, it ALWAYS results in an ObjectDisposedException on the Begin/EndReceive thread. Is there no way to Close a socket without this exception from occurring?

like image 615
shyneman Avatar asked Nov 05 '22 12:11

shyneman


1 Answers

  1. The TCP protocol guarantees the socket will close eventually unless the peer refuses to allow it to close. In which case, you should wait forever or give up, whatever's appropriate.

  2. If you close the socket after receive returns zero, that should not happen. If it is, your code is likely doing something wrong.

  3. You can't release a resource while an asynchronous operation is or might be using it. Rather than calling close, call shutdown. Don't call close until you're 100% finished with the resource.

like image 194
David Schwartz Avatar answered Nov 09 '22 10:11

David Schwartz