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.
You have to close the stream before closing the connection: tcpClient. GetStream(). Close(); tcpClient.
The common way of terminating a TCP connection is by using the TCP header's FIN flag. This mechanism allows each host to release its own side of the connection individually. Suppose that the client application decides it wants to close the connection. (Note that the server could also choose to close the connection).
When a workstation wants to close a connection with a server it sends a TCP FIN. If the client is not behaving properly and not closing its connections, they could in fact remain established on the server.
Enter "telnet + IP address or hostname + port number" (e.g., telnet www.example.com 1723 or telnet 10.17.xxx.xxx 5000) to run the telnet command in Command Prompt and test the TCP port status. If the port is open, only a cursor will show. If the port is closed, a message will say Connect failed.
You have to close the stream before closing the connection:
tcpClient.GetStream().Close(); tcpClient.Close();
Closing the client does not close the stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With