StreamReader
我创建了一个函数,它使用和接收分块的 HTTP 包TcpClient
。这是我创建的:
private string recv()
{
Thread.Sleep(Config.ApplicationClient.WAIT_INTERVAL);
string result = String.Empty;
string line = reader.ReadLine();
result += line + "\n";
while (line.Length > 0)
{
line = reader.ReadLine();
result += line + "\n";
}
for (int size = -1, total = 0; size != 0; total = 0)
{
line = reader.ReadLine();
size = PacketAnalyzer.parseHex(line);
while (total < size)
{
line = reader.ReadLine();
result += line + "\n";
int i = encoding.GetBytes(line).Length;
total += i + 2; //this part assumes that line break is caused by "\r\n", which is not always the case
}
}
reader.DiscardBufferedData();
return result;
}
对于它读取的每个新行,它会在 中添加一个额外的长度 2 total
,假设新行是由“\r\n”创建的。这适用于几乎所有情况,除非数据包含“\n”,我不知道如何将它与“\r\n”区分开来。对于这种情况,它会认为它已经读取了比实际更多的内容,从而短读了一个块并暴露PacketAnalyzer.parseHex()
在错误中。