public Message ReadMessage()
{
try
{
// If this is the end of stream, return null
if (_stream.Position == _stream.Length)
return null;
// Can we read 4 bytes?
if (_stream.Position + 4 /* size of message length field */ > _stream.Length)
return null;
// Read 4 bytes that contains message length
var messageLength = _reader.ReadInt32();
// If message length less or equlal zero - we probably read all messages
if (messageLength <= 0)
return null;
// Can we read messageLength bytes?
if (_stream.Position + messageLength > _stream.Length)
return null;
var message = new Message();
message.Magic = _reader.ReadByte();
message.Crc = _reader.ReadBytes(4);
message.Payload = _reader.ReadBytes(Message.CalculatePayloadLength(messageLength));
// Validate message content
message.Validate();
return message;
}
catch (EndOfStreamException)
{
return null;
}
}