tags:

views:

1701

answers:

5

I have a server that listens for a connection on a socket:

public class Server
{
 private Socket _serverSocket;

 public Server()
 {
  _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 1234));
  _serverSocket.Listen(1);
 }

 public void Start()
 {
  _serverSocket.BeginAccept(HandleAsyncConnectionMethod, null);
 }

 public void Stop()
 {
  //????? MAGIC ?????
 }

 //... rest of code here
}

What is the correct (clean) way to close down the socket?

Is it sufficient to call:

_serverSocket.Disconnect(true);

in the Stop() method? or is there other work that needs to happen to close the connection cleanly?

A: 

That should handle it...but if you need to make absolutely sure, you could always kill it with fire:

Not for sockets, but same idea applies., which is to close it in every way possible, then finally set the socket to null.

bigwoody
Wait, are you being funny like the codinghorror post, or do you really think it's a good idea to close it in every way possible and setting it to null?
Wim Coenen
No, do not do that.
BobbyShaftoe
+1  A: 

Since you are listening for incoming TCP connections, you could use System.Net.Sockets.TcpListener which does have a Stop() method. It does not have asynchronous operations though.

Wim Coenen
+2  A: 

TCP connection termination correctly involves a four-way handshake. You want both ends to inform the other that they're shutting down and then acknowledge each other's shutdown.

Wikipedia explains the process: http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_termination

This post explains how to make it happen in C#: http://vadmyst.blogspot.com/2008/04/proper-way-to-close-tcp-socket.html

+1  A: 

You should use Socket.Shutdown() and then Socket.Close(). Socket.Disconnect() is usually only used if you intend on reconnecting the same socket.

scottm
A: 

First, you need to make sure you're keeping track of any client sockets that were created in the process of BeginAccept. Shut those down first using the Socket.Shutdown() and Socket.Close() methods. Once those have all been shut down then do the same on the listening socket itself.

Spencer Ruport