Search code examples
c#socketsnetwork-programmingtcp

Why disconnect a TCP socket in order to connect?


I'm working on a piece of code, where a connection is made to a TCP socket.

The code contains the following excerpt:

// Close the socket if it is still open
if (_socket != null)
{
    Disconnect();
}

// Create the socket object
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

The DisConnect() method does (amongst other things):

var socket = _socket;
_socket = null;
socket.Close();

I don't understand the beginning: why disconnect in order to connect?

I have tried removing that part of the code, but then the whole thing became very unstable.

Does anybody have an idea?
Thanks


Solution

  • Once a TCP socket has been closed, it can't be reused, so a new socket is needed for a new TCP connection.

    If you want to reuse the same socket for a new TCP connection after a disconnect, you need to use the Socket.Disconnect() method with the reuseSocket parameter set to true.