In this MSDN Magazine August 2005 article Daryn Kiely explains three ways to build a TCP Server.
The third model, the async one, is the one that best fit my needs, but I'm having some throuble understanding some details of its internal working.
Question 1 - About number of Threads accepting connections
In the example, when the server is started by calling Start()
, the code creates ten ThreadPools accepting connections:
public void Start()
{
SetupServerSocket();
for (int i = 0; i < 10; i++)
_serverSocket.BeginAccept(AsyncCallback(AcceptCallback), _serverSocket);
}
I didn’t understand why you can’t use just one _serverSocket.BeginAccept
, and why the number ten.
Question 2 – About zero bytes received
In ReceiveCallback()
, if we receive zero bytes we close the connection. Why? When zero bytes are received is always considered that the client closed the connection? In the tests I’ve made here, when my client closes the connection I get an exception that is catched in SocketException. Am I missing something here?
Question 3 – About the need to BeginReceive again
After something is received in socket it's put back to BeginReceive. Why do we need to start receiving again? Shouldn’t this be automatically?
Question 4 – About buffer size
A buffer of 255 bytes is used. I understand that if a message has greater length than buffer size it gets fragmented in multiple receives. Should I set a buffer size big enough to guarantee that no message will get fragmented, or I must provide code to deal with message fragmentation (to join multiples receives in a single buffer)?