gpt4 book ai didi

c# - 令人沮丧的 TCP 序列化异常 : Binary stream '0' does not contain a valid BinaryHeader

转载 作者:可可西里 更新时间:2023-11-01 02:47:47 26 4
gpt4 key购买 nike

我在 how to send large objects over TCP 上发布了一个问题似乎主要问题已解决,但现在经常我得到另一个异常:

Binary stream '0' does not contain avalid BinaryHeader. Possible causesare invalid stream or object versionchange between serialization anddeserialization.

问题仍然在我的 Receive 方法中:

public Message Receive()
{
if (_tcpClient == null || !_tcpClient.Connected)
{
throw new TransportException("Client Not Connected");
}

// buffers
byte[] msgBuffer;
byte[] sizeBuffer = new byte[sizeof(int)];

// bites read
int readSize = 0;
// message size
int size = 0;

MemoryStream memStream = new MemoryStream();
NetworkStream netStream = _tcpClient.GetStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
// Read the message length
netStream.Read(sizeBuffer, 0, sizeof(int));

// Extract the message length
size = BitConverter.ToInt32(sizeBuffer, 0);
msgBuffer = new byte[size];

// Fill up the message msgBuffer
do
{
// Clear the buffer
Array.Clear(msgBuffer, 0, size);

// Read the message
readSize += netStream.Read(msgBuffer, 0, _tcpClient.ReceiveBufferSize);

// Write the msgBuffer to the memory streamvb
memStream.Write(msgBuffer, 0, readSize);

} while (readSize < size);

// Reset the memory stream position
memStream.Position = 0;

// Deserialize the message
return (Message)formatter.Deserialize(memStream); // <-- Exception here

}
catch (System.Exception e)
{
if (_tcpClient == null || !_tcpClient.Connected)
{
throw new TransportException("Client Not Connected");
}
else
{
throw e;
}
}
}

与此示例相关的其余代码可以在我的 original question 中找到.

有人知道导致此异常的原因以及如何避免吗?

更新

Read 更改为一次最多读取 _tcpClient.ReceiveBufferSize 字节,而不是尝试读取完整的消息大小(可能大于缓冲区大小),虽然异常的频率略有下降,但它仍然经常发生。

最佳答案

让我建议您稍微简化一下代码:

public Message Receive()
{
try
{
if (_tcpClient == null || !_tcpClient.Connected)
{
throw new TransportException("Client Not Connected");
}

using (var stream = _tcpClient.GetStream())
using (var reader = new BinaryReader(stream))
{
int size = reader.ReadInt32();
byte[] buffer = reader.ReadBytes(size);
using (var memStream = new MemoryStream(buffer))
{
var formatter = new BinaryFormatter();
return (Message)formatter.Deserialize(memStream);
}
}
}
catch (System.Exception e)
{
if (_tcpClient == null || !_tcpClient.Connected)
{
throw new TransportException("Client Not Connected");
}
throw e;
}
}

此外,如果您这样做是出于娱乐和/或教育目的,那也没关系,但在实际项目中,您可能应该考虑使用 WCF 以便通过网络传输对象。

关于c# - 令人沮丧的 TCP 序列化异常 : Binary stream '0' does not contain a valid BinaryHeader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3606507/

26 4 0