Click here to Skip to main content
11,921,353 members (64,291 online)
Rate this:
Please Sign up or sign in to vote.
See more: C# Sockets
Socket.Disconnect(bool reuse) according to MSDN enables the program to reuse the socket.

My questions are:

1) If we decide to reuse the socket does that mean it will reuse the same local end point as well? What I'm asking is would it preserve the port for that socket or would it just (I don't believe it does) save all of the object's resources ?

2) If in effect it does only save the resources, would they be allocated to the next connection and if so do the send/receive buffers automatically flush or is there some way to flush them? Does Socket.ShutDown(ShutDown.Both) do that for me on disconnect?

3) In what situation would I use Socket.Disconnect(false) because if the purpose is to reuse the socket, then what would this give me?
Posted 17-Feb-11 21:09pm
Edited 19-Feb-11 3:40am
Nish Nishant613.3K
Abdul Quader Mamun 18-Feb-11 21:08pm
Edited spelling.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Calling Socket.Disconnect(true) will internally result in Winsock's DisconnectEx function being called with the TF_REUSE_SOCKET parameter.

From the docs:
Prepares the socket handle to be reused. When the DisconnectEx request completes, the socket handle can be passed to the AcceptEx or ConnectEx function.

So it's only the socket handle that will be reused. This has nothing to do with your local endpoint.

Socket reuse is meant for fairly advanced use, where you know exactly what you are doing. It's typically used in high performance heavy traffic TCP servers. The idea being that by reusing a socket, you save some time (the time that would normally have gone into allocating that socket and its resources). So what some server developers do is to have a pre-created socket pool that they pull sockets from as and when required.

So in my opinion, for a client side TCP application there is never a good reason to reuse a socket.

In short, always use Socket.Disconnect(false) unless you really know what you are doing.

For some reason, this is not so well documented and leads to a lot of confusion.
Espen Harlinn 19-Feb-11 10:10am
Good answer :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 553
1 Dave Kreskowiak 245
2 phil.o 160
3 KrunalRohit 134
4 Sergey Alexandrovich Kryukov 132
0 OriginalGriff 6,951
1 KrunalRohit 4,530
2 Sergey Alexandrovich Kryukov 3,171
3 George Jonsson 2,840
4 Suvendu Shekhar Giri 2,181

Advertise | Privacy | Mobile
Web04 | 2.8.151120.1 | Last Updated 19 Feb 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100