C#通过网络序列化和发送
问题描述:
我想序列化一个类并通过tcp发送它。这没有问题,但是在客户端应用程序中反序列化流时出现异常。
这就是我的代码:
Hi,
I want to serialize a class and send it over tcp. Thats no problem, but I get an exception while deserializing the stream in the client application.
Thats my code:
[Serializable]
internal class SendObj1
{
public int cmd;
public string msg;
}
public class SendObj
{
public int cmd;
public string msg;
public byte[] ToByte(int Command)
{
SendObj1 obj1 = new SendObj1();
obj1.cmd = Command;
XmlSerializer xs = new XmlSerializer(typeof(SendObj1));
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, obj1);
return ms.ToArray();
}
public byte[] ToByte(int Command, string Message)
{
SendObj1 obj1 = new SendObj1();
obj1.cmd = Command;
obj1.msg = Message;
XmlSerializer xs = new XmlSerializer(typeof(SendObj1));
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, obj1);
return ms.ToArray();
}
public SendObj ToObj(byte[] buffer)
{
SendObj1 obj = new SendObj1();
try
{
XmlSerializer xs = new XmlSerializer(typeof(SendObj1));
MemoryStream ms = new MemoryStream();
obj = (SendObj1) xs.Deserialize(ms);
msg = obj.msg;
cmd = obj.cmd;
}
catch (Exception e)
{
}
return this;
}
答
例外情况说未找到根元素。由于您使用的是XmlSerialization,因此需要设置RootNode。更改可序列化类如下所示
The exception says Root Element is not found. Since your are using XmlSerialization you need to set the RootNode. change the serializable class as below
[Serializable]
[XmlRoot]
public class SendObj1
{
[XmlElement]
public int cmd = 0;
[XmlElement]
public string msg = string.Empty;
}
/ EDIT
反序列化部分不完整,需要传递缓冲区反序列化流之前的内存流
/EDIT
The deserialization part is incomplete, you need to pass the buffer to memory stream before deserialize the stream
XmlSerializer xs = new XmlSerializer(typeof(SendObj1));
MemoryStream ms = new MemoryStream(buffer); // this is missing in your code
obj = (SendObj1) xs.Deserialize(ms);
msg = obj.msg;
cmd = obj.cmd;