Each time a client connects to my server, I create a new instance of the class ClientObject. That new instance will start with the constructor:
public ClientObject(TcpClient _Socket, int _ConnectionID)
{
if (_Socket == null) return;
Socket = _Socket;
ConnectionID = _ConnectionID;
Socket.NoDelay = true;
Socket.ReceiveBufferSize = 4096;
Socket.SendBufferSize = 4096;
myStream = Socket.GetStream();
ReceiveBuffer = new byte[4096];
myStream.BeginRead(ReceiveBuffer, 0, Socket.ReceiveBufferSize, ReceiveCallback, null);
}
After receiving some message from the corresponding client, the asynchronous callback method ReceiveCallback is called:
private void ReceiveCallback(IAsyncResult result)
{
int readBytes = myStream.EndRead(result);
if (readBytes <= 0)
{
CloseConnection();
return;
}
byte[] newBytes = new byte[readBytes];
Buffer.BlockCopy(ReceiveBuffer, 0, newBytes, 0, readBytes);
ServerHandleData.HandleData(ConnectionID, newBytes);
myStream.BeginRead(ReceiveBuffer, 0, Socket.ReceiveBufferSize, ReceiveCallback, null);
}
Now, the important part here is the ServerHandleData.HandleData(ConnectionID, newBytes);
line (HandleData is a static method).
Let's assume at least 2 clients sent messages. Then this static method will be called more than once.
In that case, will we be running on multiple threads?
Or will each call wait for the previous one to finish? In that case, would it be possible to create a more efficient model that deals with clients concurrently?
Thanks!