简体   繁体   English

HttpWebResponse流读取不均匀的块

[英]HttpWebResponse Stream reading in uneven chunks

I am using the stream from HttpWebRequest.GetResponse().GetResponseStream() to read data from a streaming web API. 我正在使用HttpWebRequest.GetResponse().GetResponseStream()中的流从流式Web API读取数据。 I use Begin / EndRead on the stream with a buffer of 65K bytes. 我在带有65K字节缓冲区的流上使用Begin / EndRead I can see that data is being returned in the following pattern: 我可以看到数据以以下模式返回:

16383 bytes read.
1 bytes read.
16383 bytes read.
1 bytes read.
16383 bytes read.
1 bytes read.
etc...

Obviously the 1 byte reads introduce a lot of inefficiency in the process, and the buffer size I provide is large enough to fit 16384 bytes or more. 显然,读取1字节会导致过程效率低下,并且我提供的缓冲区大小足以容纳16384个字节或更多。 Is there anything I can do as a client to improve this or is simply up to the server how it's streaming data to me? 作为客户端,我可以做些什么来改善此情况,还是取决于服务器如何将数据流式传输给我?

The reader code is basically: 读者代码基本上是:

var buffer = new byte[65536];
using (var stream = response.GetResponseStream()) {
    while (true) {
        var bytesRead = await AsyncRead(stream.BeginRead, stream.EndRead, buffer);
        Console.WriteLine($"{bytesRead} bytes read.");
        // do something with the bytes
    }
}

where AsyncRead just calls BeginRead(buffer, 0, buffer.Length, callback, null) , then EndRead in the callback and returns the return value of EndRead . 其中AsyncRead仅调用BeginRead(buffer, 0, buffer.Length, callback, null) ,然后在回调中调用EndRead并返回EndRead的返回值。

BTW this is on .NET 4.0, no HttpClient. 顺便说一句,这是在.NET 4.0上,没有HttpClient。

What exactly are you trying to achieve by sending the HTTPWebRequest to the target server? 您到底想通过将HTTPWebRequest发送到目标服务器来实现什么?

Are you trying to read a live response from the server after asking the server for data or initializing a request between your client application and the target server? 您是在询问服务器数据或初始化客户端应用程序与目标服务器之间的请求之后,尝试从服务器读取实时响应吗? If you are try to send an HTTPWepRequest and an HTTPWebResponse to the target server then convert the response given from the server to a stream then use System.IO.StreamReader to read the in-coming stream! 如果您尝试将HTTPWepRequest和HTTPWebResponse发送到目标服务器,则将服务器提供的响应转换为流,然后使用System.IO.StreamReader读取传入的流!

Then just to be on the safe side convert the stream that was read by the System.IO.StreamReader method into UTF-8 if that is your overall goal! 为了安全起见,如果这是您的总体目标,则将System.IO.StreamReader方法读取的流转换为UTF-8!

After converting to UTF-8 you can now print the output stream into a string value which you can output to console or wherever you want to send the output string! 转换为UTF-8后,您现在可以将输出流打印为字符串值,您可以将其输出到控制台或任何要发送输出字符串的地方!

I hope this is what you wanted if not then I have been essentially useless! 我希望这是您想要的,如果没有的话,我基本上是没有用的! :P :P

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

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