我创建了一个函数,它使用 StreamReader
和 TcpClient
接收分 block 的 HTTP 包。
这是我创建的:
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”区分开来。对于这种情况,它会认为它读取的内容比实际读取的内容多,因此会缩短读取一个 block 并将 PacketAnalyzer.parseHex()
暴露给错误。
最佳答案
(在问题编辑中回答。转换为社区维基答案。参见 What is the appropriate action when the answer to a question is added to the question itself?)
OP 写道:
SOLVED: I made the following two line-reading and stream-emptying functions and I'm back on track again.
NetworkStream ns; //..... private void emptyStreamBuffer() { while (ns.DataAvailable) ns.ReadByte(); } private string readLine() { int i = 0; for (byte b = (byte) ns.ReadByte(); b != '\n'; b = (byte) ns.ReadByte()) buffer[i++] = b; return encoding.GetString(buffer, 0, i); }
关于c# - 如何让 StreamReader.ReadLine() 区分 "\r\n"和 "\n"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10562509/