gpt4 book ai didi

c# - 通过套接字发送大型序列化对象仅在尝试增加字节数组时失败,但在使用大量字节数组时没问题

转载 作者:行者123 更新时间:2023-11-30 16:35:05 25 4
gpt4 key购买 nike

我有代码在通过套接字接收数据的同时尝试增加字节数组。这是错误的。

    public bool ReceiveObject2(ref Object objRec, ref string sErrMsg)
{
try
{
byte[] buffer = new byte[1024];
byte[] byArrAll = new byte[0];
bool bAllBytesRead = false;

int iRecLoop = 0;

// grow the byte array to match the size of the object, so we can put whatever we
// like through the socket as long as the object serialises and is binary formatted
while (!bAllBytesRead)
{
if (m_socClient.Receive(buffer) > 0)
{
byArrAll = Combine(byArrAll, buffer);
iRecLoop++;
}
else
{
m_socClient.Close();
bAllBytesRead = true;
}
}

MemoryStream ms = new MemoryStream(buffer);
BinaryFormatter bf1 = new BinaryFormatter();
ms.Position = 0;
Object obj = bf1.Deserialize(ms);
objRec = obj;

return true;
}
catch (System.Runtime.Serialization.SerializationException se)
{
objRec = null;
sErrMsg += "SocketClient.ReceiveObject " + "Source " + se.Source + "Error : " + se.Message;
return false;
}
catch (Exception e)
{
objRec = null;
sErrMsg += "SocketClient.ReceiveObject " + "Source " + e.Source + "Error : " + e.Message;
return false;
}
}

private byte[] Combine(byte[] first, byte[] second)
{
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}

错误:mscorlibError:输入流不是有效的二进制格式。起始内容(以字节为单位)为:68-61-73-43-68-61-6E-67-65-73-3D-22-69-6E-73-65-72 ...

然而,当我只是作弊并使用 MASSIVE 缓冲区大小时,它没问题。

        public bool ReceiveObject(ref Object objRec, ref string sErrMsg)
{
try
{
byte[] buffer = new byte[5000000];

m_socClient.Receive(buffer);
MemoryStream ms = new MemoryStream(buffer);
BinaryFormatter bf1 = new BinaryFormatter();

ms.Position = 0;
Object obj = bf1.Deserialize(ms);
objRec = obj;

return true;
}
catch (Exception e)
{
objRec = null;
sErrMsg += "SocketClient.ReceiveObject " + "Source " + e.Source + "Error : " + e.Message;
return false;
}
}

这真的让我很生气。我不知道为什么它不起作用。我也从此处的建议中取消了联合收割机,所以我很确定这没有做错事?

希望有人能指出我哪里不对

最佳答案

Combine 方法是增长数组的一种非常昂贵的方法,尤其是当MemoryStream 设计 来解决这个问题时;其他回复是正确的:您必须检查读取的字节数:

using(MemoryStream ms = new MemoryStream()) {
int bytesRead;
while((bytesRead = m_socClient.Receive(buffer)) > 0) {
ms.Write(buffer, 0, bytesRead);
}
// access ms.ToArray() or ms.GetBuffer() as desired, or
// set Position to 0 and read
}

当然,您可以直接从流中读取(将其传递给您的阅读器)

此外 - 如果您的序列化太大,您可以考虑使用其他编码器,例如 protobuf-net(尽管这会稍微更改代码)。这可能会解决大型对象的问题。

关于c# - 通过套接字发送大型序列化对象仅在尝试增加字节数组时失败,但在使用大量字节数组时没问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2134356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com