Use of Socket.BeginAccept/EndAccept for multiple connections

心已入冬 提交于 2019-12-19 22:09:15

问题


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.



来源:https://stackoverflow.com/questions/13350812/use-of-socket-beginaccept-endaccept-for-multiple-connections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!