我希望能够得到产品,在C#中的TCP网络数据流设置缓冲区的大小数据的长度从网络流读取之前。有一个 NetworkStream.Length
属性,但还没有实现,我不想分配一个规模巨大的缓冲区,因为它会占用太多的空间。只有这样,我虽然做这将是precede另一个讲的大小的数据传输,但是这似乎有点凌乱。什么是对我来说,去这样做的最佳方式。
I would like to be able to get the length of the data available from a TCP network stream in C# to set the size of the buffer before reading from the network stream. There is a NetworkStream.Length
property but it isn't implemented yet, and I don't want to allocate an enormous size for the buffer as it would take up too much space. The only way I though of doing it would be to precede the data transfer with another telling the size, but this seems a little messy. What would be the best way for me to go about doing this.
推荐答案
在访问的 流
取值,你平时读写小块数据(例如,一个千字节左右),或者使用的方法类似的 CopyTo从
,做适合你
When accessing Stream
s, you usually read and write data in small chunks (e.g. a kilobyte or so), or use a method like CopyTo
that does that for you.
这是使用 CopyTo从
为例流的内容复制到另一个流,并将其返回为字节[]
从方法,使用自动大小的缓冲区。
This is an example using CopyTo
to copy the contents of a stream to another stream and return it as a byte[]
from a method, using an automatically-sized buffer.
using (MemoryStream ms = new MemoryStream())
{
networkStream.CopyTo(ms);
return ms.ToArray();
}
这是code,在以同样的方式读取数据,但更多的人工,这可能是更好地为你一起工作,这取决于你在做什么的数据:
This is code that reads data in the same way, but more manually, which might be better for you to work with, depending on what you're doing with the data:
byte[] buffer = new byte[2048]; // read in chunks of 2KB
int bytesRead;
while((bytesRead = networkStream.Read(buffer, 0, buffer.Length)) > 0)
{
//do something with data in buffer, up to the size indicated by bytesRead
}
(依据这些code段从Most从流读取数据),有效的方法。
(the basis for these code snippets came from Most efficient way of reading data from a stream)
相关推荐
最新文章