TCP发送类对象反序列化错误!(遇到了新问题)

hufeikong 2010-09-26 02:05:58
上一贴,求助过这个问题,经过网友的提点,我把客户端和服务端的工程名改成一样,发送序列化对象成功了。

调试后发现一个错误:

当我序列化的对象很小的时候,发送和接收没有问题;当对象大的时候,反序列化就失败了。

序列化的类
[Serializable()]
public class ServerData
{
public string file_repospath; //文件的内容
public string type; //计算类型,"A"新增,"U"修改
}


这个对象中file_repospath非常大,当超过2048时,需要循环接受多次,接收到的内容反序列化失败。




//接收代码
byte[] bytes = new byte[2048];
int bytesread = 0;
byte[] mSumBytes = null;
//接收对象
do
{
bytesread = ns.Read(bytes, 0, bytes.Length);
mSumBytes = AddBytes(mSumBytes, bytes, bytesread);
}
while (ns.DataAvailable);
ns.Flush();
//序列化结构体对象
Object ObjTemp = Deserialize(mSumBytes);

//AddBytes函数叠加接收字节
//叠加2个byte[]:b1实际字符是满的,b2的实际字符是b2_real_data_size
static byte[] AddBytes(byte[] b1, byte[] b2, int b2_real_data_size)
{
if (b1 == null)
{
byte[] newbyte = new byte[b2_real_data_size];
Array.Copy(b2, 0, newbyte, 0, b2_real_data_size);
return newbyte;
}
else
{
int bytelong = b1.Length + b2_real_data_size;
byte[] addsum = new byte[bytelong];
Array.Copy(b1, 0, addsum, 0, b1.Length);
Array.Copy(b2, 0, addsum, b1.Length, b2_real_data_size);
return addsum;
}
}


//反序列化
/// <summary>
/// 反序列化
/// </summary>
/// <param name="data">数据缓冲区</param>
/// <returns>对象</returns>
public static object Deserialize(byte[] data)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream rems = new MemoryStream(data);
data = null;
return formatter.Deserialize(rems);
}

//序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="data">要序列化的对象</param>
/// <returns>返回存放序列化后的数据缓冲区</returns>
public static byte[] Serialize(object data)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream rems = new MemoryStream();
formatter.Serialize(rems, data);
return rems.GetBuffer();
}



哪里出了问题呢?
...全文
90 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
hufeikong 2010-09-26
  • 打赏
  • 举报
回复
全给楼上,很好的提醒了我,我就是太粗心了。
hhc123 2010-09-26
  • 打赏
  • 举报
回复
接收最少也得做个判断是否接收完毕吧

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧