Asynchronous Sockets - Handling false socket.AcceptAsync values
Posted
by David
on Stack Overflow
See other posts from Stack Overflow
or by David
Published on 2010-01-04T20:50:16Z
Indexed on
2010/05/22
5:30 UTC
Read the original article
Hit count: 431
The Socket class has a method .AcceptAsync which either returns true or false.
I'd thought the false return value was an error condition, but in the samples Microsoft provide for Async sockets they call the callback function synchronously after checking for failure, as shown here:
public void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
}
else
{
// socket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;
}
m_maxNumberAcceptedClients.WaitOne();
bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
/// <summary>
/// This method is the callback method associated with Socket.AcceptAsync operations and is invoked
/// when an accept operation is complete
/// </summary>
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);
}
Why do they do this? It defeats the purpose of asynchronous sockets and stops the method from returning.
© Stack Overflow or respective owner