Use of Socket.BeginAccept/EndAccept for multiple connections
.net, .net-4.0, asynchronous, c#, sockets
Solution
The way are doing this is correct for using asynchronous sockets. Personally, I would move your BeginAccept to right after you get the socket from the AsyncState. This will allow you to accept additional connections right away. As it is right now, the handling code will run before you are ready to accept another connection.
As Usr mentioned, I believe you could re-write the code to use await with tasks.
Problem
Unlike the synchronous `Accept`, `BeginAccept` doesn't provide a socket for the newly created connection. `EndAccept` however does, but it also stops future connections from being accepted; so I concocted the following code to allow multiple 'clients' to connect to my server: ``` serverSocket.BeginAccept(AcceptCallback, serverSocket); ``` `AcceptCallback` code: ``` void AcceptCallback(IAsyncResult result) { Socket server = (Socket)result.AsyncState; Socket client = server.EndAccept(result); // client socket logic... server.BeginAccept(AcceptCallback, server); // <- continue accepting connections } ``` Is there a better way to do this? It seems to be a bit 'hacky', as it essentially loops the async calls recursively. Perhaps there is an overhead to having multiple calls to async methods, such as multiple threads being created?