套接字编程的合适缓冲区大小是多少? [英] What is a good buffer size for socket programming?

查看:30
本文介绍了套接字编程的合适缓冲区大小是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 .Net 和套接字.服务器正在使用 Socket.Sender(bytes[]) 方法,因此它只发送整个有效负载.另一方面,我们是消费数据的客户.Socket.Receive(buffer[]).在 Microsoft(和其他公司)的所有示例中,它们似乎都坚持使用 8192 的缓冲区大小.我们已经使用了这个大小,但我们时不时地向客户端发送超过此缓冲区大小的数据.

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?

推荐答案

即使您发送的数据比这更多,也可能无法在一次 Receive 调用中使用.

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

您无法确定服务器发送了多少数据——它是一个数据流,而您只是一次读取数据块.您可以在一次 Send 调用中读取服务器发送的部分,或者可以在一次 Receive 调用中读取来自两次 Send 调用的数据.8K 是一个合理的缓冲区大小 - 不会大到您会浪费大量内存,也不会小到您必须使用大量浪费的 Receive 调用.4K 或 16K 也很可能会很好......我个人不会开始超过 16K 的网络缓冲区 - 我怀疑你很少会填满它们.

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.

您可以尝试使用一个非常大的缓冲区并记录每次调用中收到的字节数 - 这会让您了解通常可用的字节数 - 但它不会真正显示使用较小缓冲区的效果.您对使用 8K 缓冲区有什么顾虑?如果是性能,您是否有任何证据表明您代码的这方面是性能瓶颈?

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?

这篇关于套接字编程的合适缓冲区大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆