Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

tcp

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.

like image 539
TimothyP Avatar asked Jan 08 '09 17:01

TimothyP


People also ask

How do I close TcpClient?

You have to close the stream before closing the connection: tcpClient. GetStream(). Close(); tcpClient.

How TCP terminates a connection?

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).

What happens if TCP connection is not closed?

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.

How do I know if my TCP connection is working?

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.


1 Answers

You have to close the stream before closing the connection:

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

Closing the client does not close the stream.

like image 137
Ignacio Soler Garcia Avatar answered Sep 20 '22 19:09

Ignacio Soler Garcia