8

读取 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)(但仍然可以发生较小的超时)

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

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

4

2 回答 2

8

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

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

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

  3. BinaryReader众所周知,当获取的数据少于预期时会引发异常NetworkStream,而不是使用循环来检索其余部分(是的,我敢肯定,这意味着一个错误!) -详细信息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;
}

这已经为我解决了。

于 2013-08-30T11:52:11.507 回答
0

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

于 2021-03-16T19:01:54.607 回答