5

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.

3
  • 3
    Did you check the MSDN pages for both methods? Commented Jun 24, 2015 at 16:22
  • 3
    Pro answers is allways better. Maybe I've missed something? Commented Jun 24, 2015 at 16:24
  • See also regarding the proper way to clean up a Socket: stackoverflow.com/a/62204814/222054 Commented Jun 4, 2020 at 21:57

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.