public static PeerMessage DecodeMessage(byte[] buffer, int offset, int count, TorrentManager manager)
{
CreateMessage creator;
if (count < 4)
throw new ArgumentException("A message must contain a 4 byte length prefix");
var messageLength = IPAddress.HostToNetworkOrder(BitConverter.ToInt32(buffer, offset));
if (messageLength > (count - 4))
throw new ArgumentException("Incomplete message detected");
if (buffer[offset + 4] == ExtensionMessage.MessageId)
return ExtensionMessage.DecodeMessage(buffer, offset + 4 + 1, count - 4 - 1, manager);
if (!MessageDict.TryGetValue(buffer[offset + 4], out creator))
throw new ProtocolException("Unknown message received");
// The message length is given in the second byte and the message body follows directly after that
// We decode up to the number of bytes Received. If the message isn't complete, throw an exception
var message = creator(manager);
message.Decode(buffer, offset + 4 + 1, count - 4 - 1);
return message;
}