using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Mistox.Attributes; using MsgPack.Serialization; namespace Mistox { public class DataPacket { // The length of the packet header in bytes public static readonly int HeaderLength = 3; // Data Packet Properties public byte PacketType { get; set; } = 0x00; public ushort DataLength { get; set; } = 0; public byte[] PacketData { get; set; } = []; // 8b. 16b. ? // Data Packet [ Type | DataLength | Data ] // Helper classes public static byte[] Serialize( T Object ) { mPacket attribute = typeof(T).GetCustomAttribute(false); DataPacket packet = new DataPacket(); if (attribute != null) { using ( MemoryStream stream = new MemoryStream() ) { MessagePackSerializer serializer = MessagePackSerializer.Get(); serializer.Pack( stream, Object ); packet.PacketData = stream.ToArray(); packet.DataLength = (ushort)packet.PacketData.Length; return new byte[]{ packet.PacketType }.Join( BitConverter.GetBytes( packet.DataLength )).Join(packet.PacketData); } } throw new Exception( "The datastructure " + typeof(T).Name + " is not an mPacket" ); } public object Deserialize() { Type type = Type.GetType( NetworkPackets[PacketType] ); MessagePackSerializer Serilizer = MessagePackSerializer.Get(type); using( MemoryStream ms = new MemoryStream( PacketData ) ) { return Serilizer.Unpack( ms ); } } // Fills out the NetworkPacket Lookup Dictionary public static readonly Dictionary NetworkPackets = new(); public static void BuildNetworkPacketList() { Type[] allClasses = Assembly.GetExecutingAssembly().GetTypes(); foreach( Type cur in allClasses) { mPacket attribute = cur.GetCustomAttribute(false); if (attribute != null) { NetworkPackets[attribute.ID] = cur.FullName + "," + cur.Assembly.FullName; } } } } }