TCPClient and buffer sizes, best practices

Hi,

On the desktop framework I never really stopped to think about
buffer sizes when receiving data using Sockets, with all the memory… who cares.

But with the devices it’s a completely different issue.
So I’m wondering how most people deal with this, if there are any best practices etc…

For example, my code here is probably absolutely no good:

client = server.Accept();
client.ReceiveTimeout = 120000;
byte[] buffer = new byte[5000];
            
try
{
    var count = 1;
    while (count > 0)
    {
        count = client.Receive(buffer);
        if (OnDataReceived != null)
            OnDataReceived(Utility.ExtractRangeFromArray(buffer, 0, count));
    }
}
//end of snippet

First I create a buffer of 5000 bytes, even if far less data will be received.
Second if I receive more than 5000 bytes the code fails as well

A half solution would be to make the buffer bigger, but it’s not an optimal solution either…

What’s your take on this?
Perhaps I’m doing this completely wrong?

Can you tell us what you are receiving and what the utility method does? Optimisation can be very specific for different situations.

What I’m receiving is simply binary data.
The point here being that as the code is now,
I need to decide up front what the maximum packet size sent by the client will be.
I do not want to limit the maximum packet size to something as small as 1000bytes
as that really slows down communication (but in some situations it will be required)

The Utility method is from the MFToolkit and does exactly what it says,
it extracts a range of bytes from a byte array.

byte[] Utility.ExtractRangeFromArray(byte[] buffer, int offset, int count);
So that the buffer that is passed on to the event handler only contains that bytes that were read.