套接字缓冲区大小:优缺点 [英] socket buffer size: pros and cons of bigger vs smaller

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

问题描述

我以前从未真正使用过COM套接字,现在有一些代码正在侦听相当稳定的数据流(500Kb / s-2000Kb / s)。

I've never really worked with COM sockets before, and now have some code that is listening to a rather steady stream of data (500Kb/s - 2000Kb/s).

我尝试了不同的尺寸,但实际上不确定我在做什么。

I've experimented with different sizes, but am not really sure what I'm conceptually doing.

byte[] m_SocketBuffer = new byte[4048];
//vs
byte[] m_SocketBuffer = new byte[8096]; 

我正在使用的套接字是System.Net.Sockets.Socket,这是我的构造函数:

The socket I'm using is System.Net.Sockets.Socket, and this is my constructor:

new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

我的问题是:


  1. 是否存在一般交易-
  2. 如何调整缓冲区大小?

我正在像这样检索数据:

I'm retrieving the data like this:

string socketData = Encoding.ASCII.GetString(m_SocketBuffer, 0, iReceivedBytes)
while (sData.Length > 0)
{ //do stuff }




  1. 当我的阅读事件发生时,缓冲区已满?就像每当套接字缓冲区达到阈值时,那是我可以从中读取的内容吗?


推荐答案

简短版本:


  • 最佳缓冲区大小取决于很多因素,包括底层网络传输以及您自己的代码如何处理I /。 O。

  • 10的K可能适合于移动大量数据的大容量服务器。但是,如果您知道远程端点永远不会一次向您发送大量数据,则可以使用更小的数据。

  • 在I / O操作期间,固定了缓冲区,这可能导致或加剧堆碎片。对于真正大容量的服务器,分配非常大的缓冲区(大于85,000字节)可能是有意义的,以便从大对象堆中分配缓冲区(该大对象堆没有碎片问题,或者处于永久状态)。碎片,具体取决于您如何看待它:)),然后仅对每个给定的I / O操作使用每个大缓冲区的一部分。

关于:您的具体问题:



  1. 对于大型还是大型?小缓冲区?


也许最明显的是平常:大于实际缓冲区的缓冲区需要只是浪费空间。

Probably the most obvious is the usual: a buffer larger than you will ever actually need is just wasting space.

使缓冲区过小会导致更多的I / O操作,可能会迫使执行更多的线程上下文切换(取决于您执行I / O的方式),并且肯定会增加必须执行的程序语句的数量。

Making buffers too small forces more I/O operations, possibly forcing more thread context switches (depending on how you are doing I/O), and for sure increasing the number of program statements that have to be executed.

当然还有其他折衷方案,b

There are other trade-offs of course, but to go into each and every one of them would be far too broad a discussion for this forum.



  1. 如何调整缓冲区大小?您应该使用什么作为量规?


我从一个看起来合理的尺寸开始,然后从那里进行实验。在各种负载测试方案中调整缓冲区大小(增加和减少),以查看对性能是否有影响。

I'd start with a size that seems "reasonable", and then experiment from there. Adjust the buffer size in various load testing scenarios, increasing and decreasing, to see what if any effect there is on performance.



  1. 当缓冲区已满时,我的读取事件会发生吗?就像套接字缓冲区达到阈值时一样,那是我可以从中读取的时间吗?


从套接字读取数据后,网络层将尽可能多地将数据放入缓冲区。如果有更多可用数据,它将填充缓冲区。如果可用数据不足,将不填充缓冲区而完成操作(但总是在将至少一个字节放入缓冲区&hellip中时;读取操作完成且长度为零的唯一时间是连接正在建立时)关闭)

When you read from the socket, the network layer will put as much data into your buffer as it can. If there is more data available than will fit, it fills the buffer. If there is less data available than will fit, the operation will complete without filling the buffer (but always when at least one byte has been placed into the buffer…the only time a read operation completes with zero-length is when the connection is being shut down)

这篇关于套接字缓冲区大小:优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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