c# - 如何让 StreamReader.ReadLine() 区分 "\r\n"和 "\n"?

标签 c# http networking tcp

我创建了一个函数,它使用 StreamReaderTcpClient 接收分 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/

相关文章:

c# - AutoMapper - 创建将 Cu​​stomer 和 Person 组合到 CustomerModel 中的映射

c# - 自动映射时可以展平对象的一部分

http - Go 中 'net/http' 中的 request.FormValue 为空

apache - 使用本地网络中的 xampp 服务器托管站点,无需端口转发

java - java的异步传输模式

c# - 按名称 (ID) C# for ASP.NET 查找文本框

c# - 如何在C#中加密/解密url

javascript - IE11 不发送 HTTP POST 数据

android - 使用 Android SDK 发布多部分请求

docker - 无法使用https/443从kubernetes Pod中获取/ curl