How to properly and completely close/reset a TcpClient connection?

TimothyP picture TimothyP · Jan 8, 2009 · Viewed 108.5k times · Source

What is the correct way to close or reset a TcpClient connection? We have software that communicates with hardware but sometimes something goes wrong and we are no longer to communicate with it, until we restart the software.

I have tried forcing TcpClient.Close() and even setting it to null but that doesn't work. Only a complete restart of the software works.

Suggestions?


I can't use the using keyword because TpcClient is only defined in one location, but used throughout the library. (And there is only one connection at any given time)

It's a library that handles communication. The software itself can call the ResetConnection() method of the Controller class (which represents the hardware).

It currently looks like

if (tcpClient != null)
{
    tcpClient.Close();
    tcpClient = null;
}

Now from what I've read here I should use tcpClient.Dispose() instead of " = null"

I'll give that a try and see if it makes a difference.

Answer

Ignacio Soler Garcia picture Ignacio Soler Garcia · Dec 30, 2009

You have to close the stream before closing the connection:

tcpClient.GetStream().Close();
tcpClient.Close();

Closing the client does not close the stream.