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.
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.
Have you tried calling TcpClient.Dispose() explicitly?
And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?
Closes a socket connection and allows for re-use of the socket:
Despite having all the appropriate
using
statements, callingClose
, having some exponential back off logic and recreating theTcpClient
I've still been seeing issues where the application cannot recover the TCP connection without an application restart. It keeps failing with aSystem.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host
.But there is an option
LingerState
on theTcpClient
that appears it may have solved the issue (might not know for a few months as my own hardware setup only fails about that often!). See MSDN.You have to close the stream before closing the connection:
Closing the client does not close the stream.
The correct way to close the socket so you can re-open is:
The Boolean parameter indicates if you want to reuse the socket: