Brod.Messages.MessageReader.ReadMessage C# (CSharp) Method

ReadMessage() public method

Message that was correctly read, or null if end of stream found
public ReadMessage ( ) : Message
return Message
        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;
            }
        }

Usage Example

Example #1
0
 /// <summary>
 /// Read messages from this message block
 /// </summary>
 public IEnumerable<Message> ReadMessages()
 {
     using (var reader = new MessageReader(new BinaryMemoryStream(Data)))
     {
         Message message;
         while ((message = reader.ReadMessage()) != null)
             yield return message;
     }
 }
All Usage Examples Of Brod.Messages.MessageReader::ReadMessage