views:

118

answers:

1

What is the best way to accept new sockets in async way.

First way:

while (!abort && listener.Server.IsBound)
{  
  acceptedSocketEvent.Reset();  
  listener.BeginAcceptSocket(AcceptConnection, null);  

  bool signaled = false;  
  do  
  {  
     signaled = acceptedSocketEvent.WaitOne(1000, false);
  } while (!signaled && !abort && listener.Server.IsBound);
}

where AcceptConnection should be:

private void AcceptConnection(IAsyncResult ar)
{
    // Signal the main thread to continue.
    acceptedSocketEvent.Set();

    Socket socket = listener.EndAcceptSocket(ar);
    // continue to receive data and so on...
    ....
}

or Second way:

listener.BeginAcceptSocket(AcceptConnection, null);
while (!abort && listener.Server.IsBound)
{  
   Thread.Sleep(500);
}

and AcceptConnection will be:

private void AcceptConnection(IAsyncResult ar)
{
    Socket socket = listener.EndAcceptSocket(ar);
    // begin accepting next socket
    listener.BeginAcceptSocket(AcceptConnection, null);
    // continue to receive data and so on...
    ....
}

What is your prefered way and why?

+1  A: 

I really like the second way; continuing to "BeginAccept" from the event that accepts the connection seems more readable to me. You can even attach the Listening socket to the IAsyncResult, and fetch it in your Accept event, to avoid the use of any globals.

deltreme
Thinking about second way too, but this has possibility to not call BeginAccept when some exception occurs within AcceptSocket method and this listener never accept any new connections.
psulek
The exception will be raised by calling EndAcceptSocket, which you can then catch and finally start the BeginAccept again.
deltreme