Search code examples
c#serializationtcptcpclienttcplistener

Serializing object ready to send over TCPClient Stream


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.

I've discovered the using System.Runtime.Serialization and the following documentation, but I didn't want to faff around to find that I'm doing it in long winded way.

The question: What is the best way to process and send an object over the TCP stream?

Sending and receiving.

Here's an example of my object:

// Create a new house to send
house newHouse = new house();

// Set variables
newHouse.street = "Mill Lane";
newHouse.postcode = "LO1 BT5";
newHouse.house_number = 11;
newHouse.house_id = 1;
newHouse.house_town = "London";

Solution

  • Assuming you have a class House (available on both sides of your connection) looking like this:

    [Serializable]
    public class House
    {
        public string Street { get; set; }
        public string ZipCode { get; set; }
        public int Number { get; set; }
        public int Id { get; set; }
        public string Town { get; set; }
    }
    

    You can serialize the class into a MemoryStream. You can then use in your TcpClient connection like this:

    // Create a new house to send house and set values.
    var newHouse = new House
        {
            Street = "Mill Lane", 
            ZipCode = "LO1 BT5", 
            Number = 11, 
            Id = 1, 
            Town = "London"
        };  
    
    var xmlSerializer = new XmlSerializer(typeof(House));
    var networkStream = tcpClient.GetStream();
    if (networkStream.CanWrite)
    {
        xmlSerializer.Serialize(networkStream, newHouse);
    }
    

    Of course you have to do a little more investigation to make the program running without exception. (e.g. Check memoryStream.Length not to be greater than an int, a.s.o.), but I hope I gave you the right suggestions to help you on your way ;-)