2

NetworkStream から読み取るときに byteSize を設定する必要があるサイズを把握しようとしています。小さい数または大きい数を使用することの長所と短所は何ですか?

私が見た多くの例では、256 が使用されています。なぜですか?

int byteSize = 256;

TcpListener server = new TcpListener(IPAddress.Any, 9999);
server.Start();
Byte[] bytes = new Byte[byteSize];

TcpClient client = server.AcceptTcpClient();

NetworkStream stream = client.GetStream();
int i = 0;

while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    // Do stuff with the stream
}
4

3 に答える 3

3

Make it too small and you'll lose some efficiency from .NET having to make an operating system call more frequently to refill the buffer. Make it too big and you waste some memory.

It is not that critical but 256 is on the low end. A very common I/O buffer size is 4096 bytes. It is a magic number in Windows, the size of a memory page. Albeit that the buffer will exactly straddle one page only by accident.

于 2013-05-10T22:46:23.873 に答える
0

Whatever you set it according to your code i is the actual bytes read from socket, so a byteSize doesn't help you if i is pretty much smaller than byteSize.

Inside your while you should check if i is smaller that byteSize and if so, copy the first i bytes of your byte (byte array) to a safe place i.e a memory stream or a file stream and continue to read socket to get to the end of network stream (where i = 0). 1024, 2048 and 4096 seems good depending on your network speed, available memory and threads which are using such a buffer. For example using 100 threads with 1024 buffer size cost you 100 KB of RAM which is nothing at today's hardware scale.

Personally most of the times use a smart buffer, I mean at run time I check read amount against buffer size and correct it to get a better result (albeit if it worth according to the project).

于 2013-05-10T22:42:50.747 に答える