Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way of closing and cleaning up a Socket connection?

Tags:

I am a bit confused by the cornucopia of related methods on the Socket object that supposedly close and clean up a socket connection. Consider the following:

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("192.168.1.22", 8333);
socket.Send(Encoding.UTF8.GetBytes("hello"));

// now for the closing fun
socket.Shutdown(SocketShutdown.Both);
socket.Disconnect(false);
socket.Close();
socket.Dispose();

In addition, this guy says that to really cleanly close a connection, one must execute socket.Shutdown(SocketShudown.Send), then wait for the other side to respond.

What is the correct way to close, then clean up a socket connection?

like image 805
AngryHacker Avatar asked Mar 12 '13 06:03

AngryHacker


People also ask

How do you close a socket from a client?

If you want the server to close the connection, you should use shutdown(cfd, SHUT_RDWR) and close(cfd) after, NOT close(lfd) . This lets the lfd socket open, allowing the server to wait at the accept for the next incoming connection. The lfd should close at the termination of the server.

Should you close a socket?

If the socket is a TCP socket and it is connected, then the TCP connection will not be closed unless the socket is closed or shutdown() is called. Therefore, in this case, you should at least make sure to call shutdown() if you can't close the socket.

Why do sockets close?

The "socket closed" error indicates that the connection was lost outside of the control or awareness of the Driver. There can be a number of reasons for that, for example: network failure. firewall timeout.


1 Answers

Closing socket closes the connection, and Close is a wrapper-method around Dispose, so generally

socket.Shutdown(SocketShutdown.Both);
socket.Close();

should be enough. Some might argue, that Close implementation might change one day (so it no longer calls Dispose), and you should call Dispose manually after calling Close, but i doubt thats gonna happen, personally :)

Alternatively, consider using using (yeh):

using (var socket = new Socket(...))
{
    ....
    socket.Shutdown(SocketShutdown.Both);
    socket.Close();
}
like image 115
Nikita B Avatar answered Oct 08 '22 06:10

Nikita B