tags:

views:

2242

answers:

7

Hi,

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?

+1  A: 

Have you tried calling TcpClient.Dispose() explicitly?

And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?

chakrit
There is only one connection, and I closed it but I did not dispose it... does that make a difference? (I suppose it does, just asking :-)
TimothyP
+7  A: 

Use word: using. A good habit of programming.

using (TcpClient tcpClient = new TcpClient())
{
     //operations
     tcpClient.Close();
}
mykhaylo
A: 

I'd guess that you aren't providing a way to reinitialize your TcpClient variable. It's probably initialized in a form load event or in the constructor of the form. Meaning, the only way to reinitialize it to reopen the application which calls the form_load event and the constructor.

scottm
A: 

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.

TimothyP
+1  A: 

Except for some internal logging, Close == Dispose.

Dispose calls tcpClient.Client.Shutdown( SocketShutdown.Both ), but its eats any errors. Maybe if you call it directly, you can get some useful exception information.

jyoung
+2  A: 

Closes a socket connection and allows for re-use of the socket:

tcpClient.Client.Disconnect(false);
Justin Tanner
+3  A: 

You have to close the stream before closing the connection:

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

Closing the client does not close the stream.

SoMoS
The reference for this answer is at http://support.microsoft.com/kb/821625
WooWaaBob