What is a good buffer size for socket programming?

Even if you’re sending more data than that, it may well not be available in one call to Receive.

You can’t determine how much data the server has sent – it’s a stream of data, and you’re just reading chunks at a time. You may read part of what the server sent in one Send call, or you may read the data from two Send calls in one Receive call. 8K is a reasonable buffer size – not so big that you’ll waste a lot of memory, and not so small that you’ll have to use loads of wasted Receive calls. 4K or 16K would quite possibly be fine too… I personally wouldn’t start going above 16K for network buffers – I suspect you’d rarely fill them.

You could experiment by trying to use a very large buffer and log how many bytes were received in each call – that would give you some idea of how much is generally available – but it wouldn’t really show the effect of using a smaller buffer. What concerns do you have over using an 8K buffer? If it’s performance, do you have any evidence that this aspect of your code is a performance bottleneck?

Leave a Comment