Sending and receiving custom objects using Tcpclient class in C#
<p>I have a client server application in which the server and the client need to send and receive objects of a custom class over the network. I am using TcpClient class for transmitting the data. I am serializing the object at the sender side and sending the resulting stream of bytes to the receiver. But at the receiver, when I try to de-serialize the bytes received, it throws Serialization Exception and the details are :</p>

<blockquote>
  <p>The input stream is not a valid
  binary format. The starting contents
  (in bytes) are:
  0D-0A-00-01-00-00-00-FF-FF-FF-FF-01-00-00-00-00-00
  ...</p>
</blockquote>

<p>My server code that serializes the object is:</p>

<pre><code>byte[] userDataBytes;
MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(ms, new DataMessage());
userDataBytes = ms.ToArray();
netStream.Write(userDataBytes, 0, userDataBytes.Length);
</code></pre>

<p>The client code that de-serializes it is:</p>

<pre><code>readNetStream.Read(readMsgBytes, 0, (int)tcpServer.ReceiveBufferSize);
MemoryStream ms = new MemoryStream(readMsgBytes);
BinaryFormatter bf1 = new BinaryFormatter();
ms.Position = 0;
object rawObj = bf1.Deserialize(ms);
DataMessage msgObj = (DataMessage)rawObj;
</code></pre>

<p>Please help me to solve this problem and possibly suggest any other method to transmit objects of custom classes across network using TcpClient in C#.</p>

<p>Thanks,
Rakesh.</p>
