从不知道要多少期待的流中读取[c#]

fla*_*mey 1 c# arrays stream

当我事先不知道会有多少数据进入时,如何从流中读取?现在我只选了一个偏高的数字(如下面的代码所示),但不能保证我不会得到更多.

所以我在循环中一次读取一个字节,每次调整数组大小?听起来太大了调整: - /

TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(ip, port);

Stream stm = tcpclnt.GetStream();

stm.Write(cmdBuffer, 0, cmdBuffer.Length);

byte[] response = new Byte[2048];
int read = stm.Read(response, 0, 2048);

tcpclnt.Close();
Run Code Online (Sandbox Code Playgroud)

ste*_*hbu 6

MemoryStream是你的朋友

http://msdn.microsoft.com/en-us/library/system.io.memorystream
Run Code Online (Sandbox Code Playgroud)

构造没有默认大小,它将自动调整大小.然后循环,因为你建议每次读取合理数量的数据.我通常选择MTU作为默认缓冲区大小.

获取它创建的底层byte []数组调用

memoryStreamInstance.GetBuffer() 
Run Code Online (Sandbox Code Playgroud)