【问题标题】:C# BinaryReader.ReadChar throws "System.ArgumentException: The output char buffer is too small" when reading NetworkStreamC# BinaryReader.ReadChar 在读取 NetworkStream 时抛出“System.ArgumentException:输出字符缓冲区太小”
【发布时间】:2013-08-30 10:21:52
【问题描述】:

在读取C#NetworkStream(从流式TCP套接字)时,BinaryReader.ReadChar偶尔会抛出异常System.ArgumentException: The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)'

所有缓冲区都有其默认大小(没有一个是手动设置的),设置更大的缓冲区大小不会影响问题。

什么是完全令人沮丧的:

  • 使用断点并通过ReadChar调用逐步遍历行时不会发生异常

  • 如果ReadChar 前面有Thread.Sleep(1000),则不会发生异常(但在较小的超时情况下仍会发生)

  • FileStream 上使用 BinaryReader 时不会发生异常,其中存储了 TCP 服务器应答的所有精确字节。

那么,从套接字流中缓冲单个字符的时间相关问题是什么?

【问题讨论】:

    标签: c# networkstream binaryreader


    【解决方案1】:

    我也有这个问题。以下是关于它的一些事实:

    1. System.ArgumentException: The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)' 已知与 UTF-8 编码问题(无效字符代码)有关,而不是与缓冲问题有关 - Detials here

    2. NetworkStreamRead 和其他方法)已知仅返回系统网络缓冲区中已经存在的字节数,而不是阻塞直到收到所有请求的数据 - Details here。因此,需要在循环中使用Read 来获取所有请求的数据

    3. 已知BinaryReader 在从NetworkStream 获取的数据少于预期时会引发异常,而不是使用循环来检索其余部分(是的,我敢肯定,这意味着一个错误!) - Details here

    因此,我的解决方案是部分重新实现 BinaryReader(我已将我的班级称为 BinReader)添加一些有用的功能并使用循环制作正确的 Read 方法:

    public int Read( byte[] buf, int off, int count ) {
        int read = 0;
        while( read < count ) {
            int toread = count - read;
            int portion = BaseStream.Read( buf, off, toread );
            read += portion;
            off += portion;
        }
        return read;
    }
    

    这已经为我解决了。

    【讨论】:

      【解决方案2】:

      我不确定这是否是解决此问题的正确方法,但将 reader.ReadChar() 更改为 Convert.ToChar(reader.ReadByte()) 似乎对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-13
        • 1970-01-01
        相关资源
        最近更新 更多