Serializing object ready to send over TCPClient Stream

后端 未结 5 1267
忘掉有多难
忘掉有多难 2021-01-03 03:05

I\'ve got a server and client set up using TcpListener and TcpClient.

I want to send an object to my server application for processing.

5条回答
  •  旧时难觅i
    2021-01-03 03:27

    How would you deserialize the xml House stream back to a House object on the receiving end? I'm refering to the solution given in Fischermaen's answer.

    On my recieving end I can see a string representation in my Output window by using the following:

    ASCIIEncoding encoder = new ASCIIEncoding();
                System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
    

    Thank you in advance.

    EDIT *

    Ok well this solution has worked for me. Might need some tidying up.

    Here's a method to deserialize a string:

    public static T DeserializeFromXml(string xml)
        {
            T result;
            XmlSerializer ser = new XmlSerializer(typeof(T));
            using (TextReader tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }
    

    Then from my TPC/IP Recieving end I call the method like so:

    TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
    
    
            byte[] message = new byte[4096];
            int bytesRead;
    
            while (true)
            {
                bytesRead = 0;
    
                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }
    
                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }
    
    
                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
    
                House house = DeserializeFromXml(encoder.GetString(message, 0, bytesRead));
    
                //Send Message Back
                byte[] buffer = encoder.GetBytes("Hello Client - " + DateTime.Now.ToLongTimeString());
    
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }
    
            tcpClient.Close();
        }
    

提交回复
热议问题