Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to close a TCP connection

I have a TcpClient object which sends some data to server, using its underlying NetworkStream.Write(). Therefor, I have:

TcpClient server = new TcpClient(serverName, 50001);

/* ... */

NetworkStream stream = server.GetStream();

Now, when a button is pressed, the connection should close. What is the right way to close the connection? The MSDN docs say that closing the TcpClient (with .Close()) does not in fact close the socket, only the TcpClient resources (that's at least the way I understood the docs).

So, would doing the next code correctly close the connection?

stream.Close();
server.Close();

Is this enough, or should I first check (somehow) if the stream (or server) can be closed (in case the connection is half-open or something)...

Even more, NetworkStream.Close() MSDN docs states that it releases resources (even sockets), so maybe closing the stream would be enough, taken that I prevent using the TcpClient after that point.

What is the right approach?

like image 300
Kornelije Petak Avatar asked Nov 20 '09 09:11

Kornelije Petak


People also ask

What is 4 way close in TCP?

The four-way handshake works as a pair of two-way Handshakes. Where, the first phase is, when the client sends the FIN flag to the server, and in return, the server sends the ACK flag as acknowledgment. At this point, the client is in the waiting state, it is waiting for the FIN flag from the server.

What is end to end connection in TCP?

TCP is a transport level protocol of the Internet that provides reliable, end-to-end communication between two processes. The requesting process, often known as the client, requests services from the server process.

How do I close a TCP connection in Linux?

Use tcpkill command to kill specified in-progress TCP connections. It is useful for libnids-based applications which require a full TCP 3-whs for TCB creation.


1 Answers

As the docs say:

Calling this method will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created.

So server.Close(); will be enough.

Closing the NetworkStream first will never hurt though.

By the way, if you happen to be using the TcpClient only in one method, wrap it in a using( ) statement so that you're sure Dispose() (equivalent to Close()) is called on it, even if exceptions are thrown etc.

like image 94
Joren Avatar answered Oct 23 '22 23:10

Joren