/// <summary> /// Attempt to get a packet from the given buffer /// </summary> /// <param name="bytes">The buffer to use</param> /// <param name="start">The index from which to start reading from the buffer</param> /// <param name="count">The total amount of bytes in the buffer</param> /// <param name="used">The amount of bytes it used to get a packet</param> /// <param name="packet">The deserialized packet if there was a match</param> /// <returns>Returns if there was a packet deserialized or not</returns> public bool TryGetPacket(byte[] bytes, int start, int count, out int used, out IPacket packet) { foreach (var type in registeredTypes) { if (!type.IsMatch(bytes, start, count)) { continue; } packet = type.Clone(); packet.Deserialize(bytes, start, count, out used); return(true); } used = 0; packet = default; return(false); }
private static IPacket DeserializeBody(PacketHeader header, byte[] buffer, int bytesTransferred) { int transferredBodyBytes = bytesTransferred - PacketHeader.Size; if (header.Length != transferredBodyBytes) { throw new Exception($"Packet Length is different (packetType: {header.PacketType}"); } byte[] bodyBytes = buffer .Skip(PacketHeader.Size) .ToArray(); Type creationType = FindPacket(header.PacketType); IPacket packet = (IPacket)Activator.CreateInstance(creationType); packet.Deserialize(bodyBytes); return(packet); }