Mohamad Ghanem
Mohamad Ghanem

Reputation: 599

Convert Object to array of Bytes

I have a server which communicates with Clients using a TCP Sockets .

I want to send an object from one of the client (Sender) to server which sends this object to another client (Receiver )

the object contains fields of different types like this

Class Test {
      public string key;
      public int id;
      public string message;
      public Test ()
      {
         // constructor code
      }

}

my question is how to convert the object to array of bytes, and when receive this array of bytes in Receiver how to do the opposite operation (convert from array of bytes to objects)?

Upvotes: 3

Views: 681

Answers (1)

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181430

You need to serialize your object. There are plenty of ways of doing that in C#.

You can serialize your object to binary bytes, XML or custom forms. If you want binary bytes (apparently that's what you're looking for) you can use BinaryFormatter class.

From the MSDN example:

Test test = new Test();
FileStream fs = new FileStream("output", FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try 
{
    formatter.Serialize(fs, test); 
}
catch (SerializationException e) 
{
    Console.WriteLine("Failed to serialize. Reason: " + e.Message);
    throw;
}
finally 
{
    fs.Close();
}

Of course, instead of a FileStream object you will use a socket output stream to send data.

If you are considering multiple platforms, I would suggest you use an XML based serialization so you won't run into issues related to platform endianness (byte order).

Upvotes: 1

Related Questions