I am using C#'s async Sockets and use BeginReceive to read data from the Socket into a byte[]-Buffer of 8192 bytes. But what happens, when new packet come in before BeginReceive is called again? My current setup handles about 3 incoming messages before it stops. I'm assuming that the Socket must store the incoming data somewhere before it can be processed by BeginReceive.
Do I have any control over how much data the Socket buffers before it stops?
Do I have to rely on processing the incoming messages fast enough in order not to "miss" any?
What happen, when the ProcessMessageBuffer method in the example below takes so long (for some reason) that the incoming data starts to pile up in the Socket?
public void ReadCallback(IAsyncResult ar)
{
// We have a new TCP Packet!
int bytesReceived = 0;
try
{
// The amount of bytes we have just received
bytesReceived = Socket.EndReceive(ar);
}
catch (SocketException ex)
{
// The client closed the connection
OnSocketException(new SocketExceptionEventArgs(ex));
}
if (bytesReceived > 0)
{
// We have received some data. Write it to the MessageBuffer
MessageBuffer.Write(ReceiveBuffer, 0, bytesReceived);
// Process the Messages that may be stored in the MessageBuffer
// What happens, if this takes too long?
ProcessMessageBuffer(MessageBuffer.ToArray());
// Get ready to receive more data
Socket.BeginReceive(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), null);
}
}