抱歉,标题这么模糊,我真的不知道该问题的标题是什么。基本上,当我得到传输编码所告诉的分块流时,我然后执行以下代码:
private IEnumerable<byte[]> ReceiveMessageBodyChunked() {
readChunk:
#region Read a line from the Stream which should be a Block Length (Chunk Body Length)
string blockLength = _receiverHelper.ReadLine();
#endregion
#region If the end of the block is reached, re-read from the stream
if (blockLength == Http.NewLine) {
goto readChunk;
}
#endregion
#region Trim it so it should end up with JUST the number
blockLength = blockLength.Trim(' ', '\r', '\n');
#endregion
#region If the end of the message body is reached
if (blockLength == string.Empty) {
yield break;
}
#endregion
int blockLengthInt = 0;
#region Convert the Block Length String to an Int32 base16 (hex)
try {
blockLengthInt = Convert.ToInt32(blockLength, 16);
} catch (Exception ex) {
if (ex is FormatException || ex is OverflowException) {
throw new Exception(string.Format(ExceptionValues.HttpException_WrongChunkedBlockLength, blockLength), ex);
}
throw;
}
#endregion
// If the end of the message body is reached.
if (blockLengthInt == 0) {
yield break;
}
byte[] buffer = new byte[blockLengthInt];
int totalBytesRead = 0;
while (totalBytesRead != blockLengthInt) {
int length = blockLengthInt - totalBytesRead;
if (bytesRead == 0) {
WaitData();
continue;
}
totalBytesRead += bytesRead;
yield return buffer;
}
goto readChunk;
}
这样做是从应该是块长度的流中读取 1 行数据,在这里和那里进行一些检查,但最终将其转换为 Int32 Radix16 整数。
从那里它基本上创建了一个 int32 的字节缓冲区作为它的长度大小。
然后它只是继续从流中读取,直到它读取与我们转换的 Int32 相同的数量。
这很好用,但是,无论出于何种原因,它在最后一次阅读时响应不正确。
它将读取确切的字节数,因为块长度非常好,并且我期望的所有数据都被读取。但它也在再次读取另一小块数据,这些数据在最后已经读取,导致我们可以说从ASWELL<!DOCTYPE html>到</html>ASWELL 的所有数据作为来自内部某处的一些数据<form>等
这是发生的事情的一个例子:
如您所见,突出显示的红色文本不应该从阅读中返回!它应该在 结束</html>
。为什么 Chunk's Length 对我说谎,我怎样才能找到合适的尺寸来阅读?
一只萌萌小番薯
相关分类