Arman Hayots
Arman Hayots

Reputation: 2508

Socket.Disconnect vs Socket.Close

What is the difference and which rules I must follow when working with socks? I'm writing simple daemon, which must listen port and do some actions.

Upvotes: 5

Views: 9293

Answers (1)

voytek
voytek

Reputation: 2222

Socket.Close calls Dispose (but it's undocumented).

When using a connection-oriented Socket, always call the Shutdown method before closing the Socket. This ensures that all data is sent and received on the connected socket before it is closed. (msdn)

Your code should looks like this (at least I'd do it like this):

using (var socket = new Socket())
{
    socket.Shutdown(SocketShutdown.Both);
    socket.Close();
}

The Disconnect method takes a single parameter bool reuseSocket , according to msdn:

reuseSocket Type: System.Boolean true if this socket can be reused after the current connection is closed; otherwise, false.

which basically means, when you set reuseSocket to false it will be disposed after you close it.

The Shutdown method will not disconnect your socket, it will just disable sending/receiving data.

Upvotes: 10

Related Questions