// deserialize a datagram-message via a specific type and byte-array data
        public DatagramMessage DeserializeMessage(Type type, byte[] data)
        {
            DatagramMessage message = Activator.CreateInstance(type) as DatagramMessage;

            if (message == null)
            {
                return(null);
            }
            MemoryStream   m = new MemoryStream(data);
            DatagramReader r = new DatagramReader(m);

            message.Deserialize(r);
            return(message);
        }
        public byte[] AnalyzeMessage(MemoryStream data)
        {
            if (data.Length - data.Position < 4)
            {
                return(null);
            }

            long           origin = data.Position;
            DatagramReader r      = new DatagramReader(data);

            ushort dmid = r.ReadUShort();
            Type   type = this.SelectMessageType(dmid);

            if (type == null)
            {
                // clear stream
                data.SetLength(0);
                data.Position = 0;
                return(null);
            }

            ushort size = r.ReadUShort();

            if (data.Length - data.Position < size)
            {
                // roll back
                data.Position = origin;
                return(null);
            }

            byte[] bytes = new byte[4 + size];
            data.Position = origin;
            if (data.Read(bytes, 0, bytes.Length) < bytes.Length)
            {
                // roll back
                data.Position = origin;
                return(null);
            }

            return(bytes);
        }
        // deserialize datagram-message via data which contains 4-byte meta-data
        public DatagramMessage DepackMessage(byte[] data)
        {
            if (data == null || data.Length < 4)
            {
                throw new Exception("Message data is null or data.Length is too small.");
            }

            MemoryStream   m    = new MemoryStream(data);
            DatagramReader r    = new DatagramReader(m);
            ushort         dmid = r.ReadUShort();
            ushort         size = r.ReadUShort();

            byte[] bytes = r.ReadBytes(size);

            Type type = this.SelectMessageType(dmid);

            if (type == null)
            {
                throw new Exception("The type of message is not found for dmid=" + dmid);
            }
            DatagramMessage message = this.DeserializeMessage(type, bytes);

            return(message);
        }