Reading from a stream without knowing how much to expect [C #]
How can I read from a stream when I don't know in advance how much data will come in? Right now, I just selected the number on the high side (like in the code below), but there is no guarantee that I won't get more.
So I am reading a byte at a time in a loop, resizing the array each time? Sounds too much to resize: - /
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();
a source to share
Putting it all together, assuming you don't end up with a HUGE (more than can fit in memory) amount of data:
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(ip, port);
Stream stm = tcpclnt.GetStream();
stm.Write(cmdBuffer, 0, cmdBuffer.Length);
MemoryStream ms = new MemoryStream();
byte[] buffer = new Byte[2048];
int length;
while ((length = stm.Read(buffer, 0, buffer.Length)) > 0)
ms.Write(buffer, 0, length);
tcpclnt.Close();
byte[] response = ms.ToArray();
As mentioned, MemoryStream
will handle the dynamic byte array allocation for you. And Stream.Read(byte[], int, int)
will return the length of the bytes found in this "read" or 0
if it reaches the end.
a source to share
MemoryStream is your friend
http://msdn.microsoft.com/en-us/library/system.io.memorystream
Construct no default size and it will autoresist. Then just a loop where you suggest reading a reasonable amount of data each time. I usually choose MTU as the default buffer size.
To get the underlying byte [] array that makes the call
memoryStreamInstance.GetBuffer()
a source to share