1

I have some C# that is successfully calling my TCP service (running on Node.js) and receiving a response. My code looks similar to this:

string html = Console.ReadLine();
Byte[] htmlBytes = System.Text.Encoding.ASCII.GetBytes(html);

TcpClient client = new TcpClient("127.0.0.1", 5000);
NetworkStream stream = client.GetStream();
stream.Write(htmlBytes, 0, htmlBytes.Length);
Console.WriteLine("Message has been sent");

Byte[] responseBytes = new Byte[50000];
int numberOfBytes = stream.Read(responseBytes, 0, responseBytes.Length);

My questions is in regarding to this code:

Byte[] responseBytes = new Byte[50000];
int numberOfBytes = stream.Read(responseBytes, 0, responseBytes.Length);

Because responseBytes is passed by reference into stream.Read(...), it must be initialized, so I've chosen a size of 50000. If the response is more than 50000, then I only receive the first 50000 bytes.

This works fine if my response is 50000 bytes or smaller, but what if I don't know what the response size will be? Is there a best practice for receiving large responses or handling a situation where the byte array returned is unknown?

ChadSC
  • 340
  • 5
  • 13
  • 1
    [This question](https://stackoverflow.com/questions/13097269/what-is-the-correct-way-to-read-from-networkstream-in-net) might also help. – Brian Jul 16 '18 at 20:19
  • Thanks, Brian. The loop in Colin's sample code was exactly what I was looking for. – ChadSC Jul 18 '18 at 13:13

1 Answers1

0

this may be super simplistic of an answer, but wouldn't it make sense to just have an arbitrary variable as a 'byte' for the size. Then as you process responses, that variable gets assigned a new value each time, before the initialization of the array?

  • I tried to pass in an uninitialized array, but I receive an error "array creation must have array size or array initializer." I believe in C#, arrays must be initialized to a specified size. – ChadSC Jul 16 '18 at 20:05
  • Hey Chad, right, but if you store the bytes into the size before then it will fix that. Should do the trick. – Jess Graham Jul 16 '18 at 22:35
  • Sorry, I'm not follow what "store the bytes into the size before then" means. My issue is that I need to declare a variable size before I know how big it actually needs to be. If you're able to mock the code, that might help clarify what you're getting at. – ChadSC Jul 18 '18 at 13:06