When reading C# NetworkStream
(from stream-type TCP socket), BinaryReader.ReadChar
occasionally throws exceptions System.ArgumentException: The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)'
All buffers have their default sizes (none of them are manually set) and setting bigger buffer sizes does not affect the issue.
And what is completely discouraging:
The exception does not occur when using breakpoint and walking step-by-step through the line with
ReadChar
callThe exception does not occur if
ReadChar
is preceded byThread.Sleep(1000)
(but can still occur with smaller timeouts)The exception does not occur when using
BinaryReader
onFileStream
, where all precise bytes of TCP-server's answer are stored.
So, what can be the time-related issue with buffering single characters from stream a socket?
I had this issue too. And here are some facts about it:
System.ArgumentException: The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)'
is known to be related to UTF-8 encoding problem (invalid character code) rather than to buffering problem - Detials hereNetworkStream
(Read
and other methods) is known to return only the amount of bytes which is already present in system network buffers instead of blocking until all requested data will be recieved - Details here. So, one needs to useRead
in a loop to get all requested dataBinaryReader
is known to throw an exception when getting less data fromNetworkStream
than it expected, instead of using a loop to retrieve the rest (and YES, I am sure, this means a bug!) - Details hereSo, my solution was to partially reimplement
BinaryReader
(I have called my classBinReader
) adding some useful features and making proper Read method with a loop:That has solved it for me.