Class DelimiterPacketReader

java.lang.Object
naga.packetreader.DelimiterPacketReader
All Implemented Interfaces:
PacketReader
Direct Known Subclasses:
AsciiLinePacketReader, ZeroDelimitedPacketReader

public class DelimiterPacketReader extends Object implements PacketReader
Class to read a byte stream delimited by a byte marking the end of a packet.

Since packets read with delimiters may potentially grow unbounded, you can also supply a maximum buffer size to prevent an attacker from causing an out of memory by continously sending data without the delimiter.

The delimiter will never appear in the packet itself.

Author:
Christoffer Lerno
  • Constructor Details

    • DelimiterPacketReader

      public DelimiterPacketReader(byte delimiter)
      Create a new reader with the default min buffer size and unlimited max buffer size.
      Parameters:
      delimiter - the byte delimiter to use.
    • DelimiterPacketReader

      public DelimiterPacketReader(byte delimiter, int maxPacketSize)
      Create a new reader with the given min and max buffer size delimited by the given byte.
      Parameters:
      delimiter - the byte value of the delimiter.
      maxPacketSize - the maximum number of bytes read before throwing an IOException. -1 means the packet has no size limit.
      Throws:
      IllegalArgumentException - if maxPacketSize < 1
  • Method Details

    • getMaxPacketSize

      public int getMaxPacketSize()
      Get the current maximum buffer size.
      Returns:
      the current maximum size.
    • setMaxPacketSize

      public void setMaxPacketSize(int maxPacketSize)
      Set the new maximum packet size.

      This method is thread-safe, but will not affect reads in progress.

      Parameters:
      maxPacketSize - the new maximum packet size.
    • nextPacket

      public byte[] nextPacket(ByteBuffer byteBuffer) throws ProtocolViolationException
      Description copied from interface: PacketReader
      Create a new packet using the ByteBuffer given.

      If there isn't sufficient data to construct a packet, return null.

      Specified by:
      nextPacket in interface PacketReader
      Parameters:
      byteBuffer - the byte buffer to use.
      Returns:
      the new packet created, or null if no packet could be created. The method will continously be called until nextPacket returns null.
      Throws:
      ProtocolViolationException - is there was an error constructing the packet.