What is a good buffer size for socket programming?

本文讨论了在网络编程中使用Socket时的最佳缓冲区大小选择。针对.NET应用中的客户端接收数据场景,探讨了不同缓冲区大小的影响,并建议了一个合理的缓冲区大小范围。

http://stackoverflow.com/questions/2811006/what-is-a-good-buffer-size-for-socket-programming

问题:

We are using .Net and sockets.

The server is using the Socket.Sender(bytes[]) method so it just sends the entire payload.

On the other side we are clients consuming the data.

Socket.Receive(buffer[]).

In all the examples from Microsoft (and others) they seem to stick with a buffer size of 8192.

We have used this size but 【every now and then不时地,常常】 we are sending data down to the clients that exceeds this buffer size.

Is there a way of determining how much data the server's sent method sent us? What is the best buffer size?

 

回答:

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?

 

转载于:https://www.cnblogs.com/chucklu/p/5279336.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值