简体   繁体   English

通过套接字对对象进行XML序列化

[英]XML serialization of objects through Sockets

My idea -> client server system, exchanges text messages (strings) through TCP sockets. 我的想法->客户端服务器系统,通过TCP套接字交换文本消息(字符串)。 I want the protocol between client and server to be based on XML. 我希望客户端和服务器之间的协议基于XML。 And because information between sockets is sent as byte , I have to cast. 而且因为套接字之间的信息以byte发送,所以我必须强制转换。 So here is what I do: Class TheMessage with property of type string . 所以这是我的工作:类TheMessage具有string类型的属性。 I make object of that class with the string to be sent as property of the object, and make it from Object to byte[] through XmlSerialization . 我使用要作为对象属性发送的字符串作为该类的对象,并通过XmlSerialization将其从Object传递到byte[] On the other side I do the vise-versa process. 另一方面,我要进行“反之亦然”的过程。 This is how I serialize and send from the client to the server: 这是我序列化并从客户端发送到服务器的方式:

msg.Message = Console.ReadLine();
byte[] writeBuff = XmlRefacrotClient.ObjectToByteArray(msg);
Stream stm = client.GetStream();
stm.Write(writeBuff, 0, writeBuff.Length);

this is the method I use for serialization: 这是我用于序列化的方法:

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;
    }
}

this is how I receive the data on the server side: 这就是我在服务器端接收数据的方式:

byte[] readBuff = new byte[1024];
s.Receive(readBuff);
String str = (XmlRefactorServer.ByteArrayToObject(readBuff)).ToString();

Console.WriteLine(str);

and this is the method for de-serialization: 这是反序列化的方法:

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;
    }
}

Everything runs smooth until the return of ByteArrayToObject method.I get InvalidOperationException with description There is an error in XML document (0, 0). 一切运行顺利,直到return ByteArrayToObject方法。我收到带说明的InvalidOperationException There is an error in XML document (0, 0). on the return xmlS.Deserialize(ms); return xmlS.Deserialize(ms); line. 线。

Any suggestions? 有什么建议么?

Try this. 尝试这个。 It's a lot cleaner: 这很干净:

  //---------------------------------------------------------------------
        public static Byte[] ObjectToByteArray<T>(T obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                XmlSerializer xmlS = new XmlSerializer(typeof(T));
                xmlS.Serialize(ms, obj);

                return ms.ToArray();
            }
        }
        //---------------------------------------------------------------------
        public static T ByteArrayObject<T>(Byte[] bObj)
        {
            using (MemoryStream ms = new MemoryStream(bObj))
            {
                XmlSerializer xmlS = new XmlSerializer(typeof(TheMessage));
                return (T)xmlS.Deserialize(ms);
            }
        }
        //---------------------------------------------------------------------
        public static void Sending(Byte[] bData)
        {
            Stream stm = client.GetStream();

            // always write size first when using TCP
            Byte[] bSize = BitConverter.GetBytes(bData.Length);
            stm.Write(bSize, 0, bSize.Length);
            stm.Write(bData, 0, bData.Length);
        }

        //---------------------------------------------------------------------
        public static void Receiving(Byte[] bData)
        {
            Byte[] bSize = new Byte[sizeof(Int32)];
            s.Read(bSize, 0, bSize.Length);

            Byte[] bData = new Byte[BitConverter.ToInt32(bSize, 0)];
            s.Read(bData, 0, bData.Length);

            TheMessage m = ByteArrayObject<TheMessage>(bData);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM