我有一个基本的异步套接字服务器。最近,我遇到了间歇性时期,其中一个连接在 TCP 对等方的回复中出现以下错误:
Exception message:
The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)' fallback 'System.Text.DecoderReplacementFallback'.
Exception stacktrace:
at System.Text.Encoding.ThrowCharsOverflow()
at System.Text.Encoding.ThrowCharsOverflow(DecoderNLS decoder, Boolean nothingDecoded)
at System.Text.UTF8Encoding.GetChars(Byte* bytes, Int32 byteCount, Char* chars, Int32 charCount, DecoderNLS baseDecoder)
at System.Text.DecoderNLS.GetChars(Byte* bytes, Int32 byteCount, Char* chars, Int32 charCount, Boolean flush)
at System.Text.DecoderNLS.GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteCount, Char[] chars, Int32 charIndex, Boolean flush)
at System.Text.DecoderNLS.GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteCount, Char[] chars, Int32 charIndex)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadLine()
at MyServer.TcpReceiveMessages()
我怀疑流量在特定的网络路由上受到破坏(其他 TcpListener 和应用程序/网络中其他地方的对等方始终保持 100% 正常通信)。可以采取哪些步骤来更好地查明并修复它?
(注意,我已经完成了数据包捕获,导致异常的传入数据包处理看起来很好,即有效负载似乎包含我想要的文本。我说看是因为有效负载的可识别部分应该在那里,但是也有一些二进制部分在被损坏时不会立即显现出来。)
监听器的简化版本:
private void TcpReceiveMessages()
{
TcpClient tcpServer = new TcpClient();
string address = "some_address";
int port = 80;
tcpServer.Connect(address, port);
StreamReader srReceiver = new StreamReader(tcpServer.GetStream());
StringBuilder wholeMsg = new StringBuilder();
string partialMsg = "";
while (tcpServer.Connected)
{
try
{
//Save a partial portion of the reply:
partialMsg = srReceiver.ReadLine();
//Reply complete:
if ( partialMsg != null && partialMsg == "")
{
response = wholeMsg.ToString() + partialMsg;
//Misc response processing code.
}
}
catch (Exception ex)
{
//Do logging that leads to the above exception message/stacktrace
}
}
}