-2

I'm making a simple program that receive UDP Packets from another program and I want to cast this packet to a class.

I have a class :

public class Packet
{
    public string MyFirstProperty {get; set;}
    public string MySecondProperty {get; set;}
    public string MyThirdProperty {get; set;}
    public OtherObject[] ObjectArray {get; set}
}

The packet that I receive are bytes array. How can I transform the packet to a class. I've heard of marshalling but I'm not experienced enough to fully understand it. What should I do.

Thank you.

  • You need to write code which reads that binary data and then converts the data to .NET strings etc. There are many options how you eventually can wrap that code into something idiomatic. But for your first try - just write the code (``Packet Parse(MemoryStream bytes)``) – BitTickler Sep 08 '17 at 19:36

2 Answers2

1

To send an object from client to server (utilizing Json.Net) ; assuming you have already done your own research and have a working UDP client/server

Client site:

c1) Packet p = new Packet();
c2) //fill the properties
c3) string json = JsonConvert.SerializeObject(p);
c4) byte[] buf = Encoding.UTF8.GetBytes(json);
c5) Send *buf* to server

Server site:

s1) Receive data from client( call it *buf*)
s2) string json = Encoding.UTF8.GetString(buf); (must be equal to json at client site)
s3) Packet p = JsonConvert.DeserializeObject<Packet>(json);
s4) Tada........

Now you can use the same algorithm to send object from server to client

PS: As long as you can send and then receive the same byte array using UDP(c5 => s1), you can get the original object back.

Eser
  • 11,700
  • 1
  • 17
  • 31
0

You need to use Serialization and De-Serialization to convert back class objects from and to Byte Array.

Here is a sample example.

public class MyClass {

   public int Id { get; set; }
   public string Name { get; set; }

   public byte[] Serialize() {
      using (MemoryStream m = new MemoryStream()) {
         using (BinaryWriter writer = new BinaryWriter(m)) {
            writer.Write(Id);
            writer.Write(Name);
         }
         return m.ToArray();
      }
   }

   public static MyClass Desserialize(byte[] data) {
      MyClass result = new MyClass();
      using (MemoryStream m = new MemoryStream(data)) {
         using (BinaryReader reader = new BinaryReader(m)) {
            result.Id = reader.ReadInt32();
            result.Name = reader.ReadString();
         }
      }
      return result;
   }

}

Link to MSDN for more on serialization

sumeet kumar
  • 2,526
  • 1
  • 12
  • 22