include these 2 lines at the top of the class file:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatter.Binary;
Here your class goes:
[Serializable] public class PacketHdr { private short packetType; private int packetLength;
public PacketHdr(short packetType, int packetLength) { this.packetType = packetType; this.packetLength = packetLength; } }
Here Function to do the Conversion:
From object to bytes:
private byte[] GetPacketBytes(PacketHdr packetHdr) { MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, packetHdr); return ms.ToArray(); }
From Byes to object:
private PacketHdr GetPacketObject(byte[] packetBytes) { MemoryStream ms = new MemoryStream(); ms.Write(packetBytes, 0, packetBytes.Length); ms.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(ms) as PacketHdr; }
Usage:
PacketHdr p = new PacketHdr(1, 2);
byte[] packetBytes = GetPacketBytes(p); // Write these bytes on Network;
Read the bytes from the Network and contruct the object from the following line:
PacketHdr p1 = GetPacketObject(packetBytes);
Make sure to Receive all the bytes from the Network before you Decerialize bytes back to object otherwise wou;ll get an exception. So you have to make a check that how many bytes are sending and how many bytes you have to receive for a successful deserialization.
I hope this will help.
Best Regards,
Rizwan aka RizwanSharp
|