我的想法-> 客户端服务器系统,通过 TCP 套接字交换文本消息(字符串)。我希望客户端和服务器之间的协议基于 XML。而且因为套接字之间的信息是作为 发送的byte
,所以我必须强制转换。所以这就是我所做的:TheMessage
具有 type 属性的类string
。我使用要作为对象属性发送的字符串来制作该类的对象,并使其从Object
到byte[]
through XmlSerialization
。另一方面,我做反之亦然的过程。
这就是我序列化并从客户端发送到服务器的方式:
msg.Message = Console.ReadLine();
byte[] writeBuff = XmlRefacrotClient.ObjectToByteArray(msg);
Stream stm = client.GetStream();
stm.Write(writeBuff, 0, writeBuff.Length);
这是我用于序列化的方法:
public static byte[] ObjectToByteArray(TheMessage obj)
{
try
{
MemoryStream ms = new MemoryStream();
XmlSerializer xmlS = new XmlSerializer(typeof(Message.TheMessage));
XmlTextWriter xmlTW = new XmlTextWriter(ms, Encoding.UTF8);
xmlS.Serialize(xmlTW, obj);
ms = (MemoryStream)xmlTW.BaseStream;
return ms.ToArray();
}
catch(Exception)
{
throw;
}
}
这就是我在服务器端接收数据的方式:
byte[] readBuff = new byte[1024];
s.Receive(readBuff);
String str = (XmlRefactorServer.ByteArrayToObject(readBuff)).ToString();
Console.WriteLine(str);
这是反序列化的方法:
public static Object ByteArrayToObject(byte[] arr)
{
try
{
XmlSerializer xmlS = new XmlSerializer(typeof(Message.TheMessage));
MemoryStream ms = new MemoryStream();
XmlTextWriter xmlTW = new XmlTextWriter(ms, Encoding.UTF8);
return xmlS.Deserialize(ms);
}
catch(Exception)
{
throw;
}
}
一切都运行顺利,直到方法。我得到return
的描述就行了。ByteArrayToObject
InvalidOperationException
There is an error in XML document (0, 0).
return xmlS.Deserialize(ms);
有什么建议么?