Use of Socket.BeginAccept/EndAccept for multiple c

2020-04-10 03:04发布

问题:

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?

回答1:

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.



回答2:

This is normal when you deal with callback-based async IO. And it is what makes it so awful to use!

Can you use C# await? That would simplify this to a simple while (true) { await accept(); } loop.