reckface
reckface

Reputation: 5858

Who shuts down the socket connection

I have a server/client socket application, and from the examples on http://msdn.microsoft.com/en-us/library/6y0e13d3.aspx it appears both the server and the client shutdown and close the connections after receiving data.Is this right? I had been using disconnect but I was unable to reopen the connection, but using the shutdown/close:

            if (_sender.Connected)
            {
                _sender.Shutdown(SocketShutdown.Both);
                _sender.Close();
            }

seems to work fine. But should this be called on both the client (initiator) and the server(recipient) sockets? Thanks

Upvotes: 1

Views: 1155

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456717

It doesn't matter which side initiates the close. If the close happens cleanly, then the other side's next read operation will read 0 bytes. If the close does not happen cleanly, then the other side's next read operation will raise an exception.

In general, it is always a good idea to expect exceptions from any socket methods (except Close, which won't raise exceptions except for fatal exceptions). Whenever you see an exception, just call Close.

P.S. Connected is useless, and Shutdown doesn't gain you anything in this case. Just call Close.

Upvotes: 0

Ryan Pedersen
Ryan Pedersen

Reputation: 3207

You need to do this on the client and the server both because they both have independent resources being used. Sockets can get messy (lots of exceptions) when they shutdown so you want to make sure that you are handling the exceptions on both the client and the server too.

Upvotes: 1

Related Questions