Using Socket.BeginAccept / EndAccept for Multiple Connections

Unlike synchronous Accept , BeginAccept does not provide a socket for a newly created connection. EndAccept however, but it also stops future connections from accepting; so I came up with the following code to allow several "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? This seems to be a little โ€œhacked," because it essentially repeats asynchronous calls cyclically.
Perhaps there is overhead associated with multiple async method calls, such as creating multiple threads?

+4
source share
2 answers

This is done correctly for using asynchronous sockets. Personally, I would move your BeginAccept right after you get the socket from AsyncState. This will allow you to immediately accept additional connections. As of now, the processing code will be launched before you are ready to accept another connection.

As Usr said, I believe that you could re-write code for use with tasks.

+3
source

This is normal when you are dealing with asynchronous callback based IO. And this is what makes it so terrible to use!

Can you use c #? This will simplify this simple while (true) { await accept(); } while (true) { await accept(); } .

+1
source

Source: https://habr.com/ru/post/1445611/


All Articles