简体   繁体   English

当响应大小未知时,通过C#调用Node.js服务

[英]Calling Node.js service via C# when the response size is unknown

I have some C# that is successfully calling my TCP service (running on Node.js) and receiving a response. 我有一些C#成功调用我的TCP服务(在Node.js上运行)并收到响应。 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. 由于responseBytes是通过引用传递到stream.Read(...) ,因此必须对其进行初始化,因此我选择了50000的大小。如果响应大于50000,则我只会收到前50000字节。

This works fine if my response is 50000 bytes or smaller, but what if I don't know what the response size will be? 如果我的响应是50000字节或更小,这会很好地工作,但是如果我不知道响应的大小会怎样呢? Is there a best practice for receiving large responses or handling a situation where the byte array returned is unknown? 是否有最佳实践来接收较大的响应或处理返回的字节数组未知的情况?

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? 然后,在处理响应时,每次在数组初始化之前为该变量分配一个新值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM