Reputation: 1709
I am trying to create an asynchronous tcp server which can handle multiple concurrent connections. Then, I have read through the example shown in MSDN:
https://msdn.microsoft.com/en-us/library/fx6588te.aspx
But it happpened that I change the asynchronous receive in AcceptCallback function to synchronous receive, so now my AcceptCallback function become:
private void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Sync receive
byte[] buff = new byte[1024];
handler.Receive(buff);
ConsumeMessage(handler, buff);
}
Then, my tcp server is not able to handle multiple concurrent connections anymore. If there are two concurrent connections, it can only connect one client, and the other one still in connection queue. After looking around, I found this article:
Asynchronous server socket multiple clients
Groo mentioned that: "To allow mulitple concurrent connections, you need to create a receive socket using handler.BeginReceive, and then call listener.BeginAccept to start listening to new clients."
Can anyone explain why we need to use AsyncReceive here to be able to handle multiple connections? If I want to use SyncReceive, is there any way to make it still able to handle multiple connections?
Upvotes: 0
Views: 948
Reputation: 8149
BeginAccept only accepts a single incoming connection. If you want to keep accepting new incoming connections, you have to call BeginAccept again in your AcceptCallback.
Having said that, I would suggest investigating high-level communication libraries or frameworks like WCF. Doing scalable low-level network programming is very tricky to do right.
Upvotes: 0
Reputation: 26436
Any thread can only do one thing at a time. By default, the Receive
call blocks until data is available, which prevents any other code (such as accepting new connections) from running on that thread.
You could of course create a thread for each separate connection, on which you can receive data synchronously, but in the end you'd be emulating how BeginReceive
and have the overhead of having to manage these threads yourself.
There are some alternatives which allow synchronous processing, such as non-blocking sockets and using Socket.Select()
, but using those is not recommended (non-blocking sockets require polling, and Socket.Select()
is tricky to get right).
Upvotes: 1