Class MqttCodec

java.lang.Object
com.codename1.io.mqtt.MqttCodec

public final class MqttCodec extends Object
Encodes and decodes MQTT 3.1.1 control packets on plain streams, so it is independent of the transport. QoS 2 packets (PUBREC, PUBREL, PUBCOMP) and a PUBLISH at QoS 2 are rejected with an MqttException.
  • Field Details

    • MAX_REMAINING_LENGTH

      public static final int MAX_REMAINING_LENGTH
      The largest remaining length the protocol can express, 268435455.
      See Also:
  • Method Details

    • encodeRemainingLength

      public static byte[] encodeRemainingLength(int value)

      Encodes a remaining length as the protocol's variable length integer.

      Parameters
      • value: 0 to 268435455
      Returns

      one to four bytes

    • encode

      public static byte[] encode(MqttPacket p) throws IOException

      Encodes a packet to its wire form.

      Parameters
      • p: the packet
      Returns

      the fixed header followed by the variable header and payload

      Throws

      MqttException when the packet cannot be represented

      Throws:
      IOException
    • write

      public static void write(MqttPacket p, OutputStream out) throws IOException

      Encodes a packet and writes it to a stream, without flushing it.

      Parameters
      • p: the packet

      • out: the destination

      Throws:
      IOException
    • packetLength

      public static int packetLength(byte[] buf, int off, int len, int maxRemaining) throws IOException

      Measures the first packet in a buffer.

      Parameters
      • buf: received bytes

      • off: where the packet starts

      • len: how many bytes are available from off

      • maxRemaining: the largest remaining length to accept

      Returns

      the total size of the packet, fixed header included, or -1 when more bytes are needed

      Throws

      MqttException when the length is malformed or above the limit

      Throws:
      IOException
    • read

      public static MqttPacket read(InputStream in, int maxRemaining) throws IOException

      Reads one packet from a stream, blocking until it is complete.

      Parameters
      • in: the source

      • maxRemaining: the largest remaining length to accept

      Returns

      the packet

      Throws

      EOFException when the stream ends, MqttException for a malformed or oversized packet

      Throws:
      IOException
    • decode

      public static MqttPacket decode(int first, byte[] body) throws IOException

      Decodes a packet from its first byte and its body.

      Parameters
      • first: the fixed header's first byte (type and flags)

      • body: the bytes after the remaining length

      Returns

      the packet

      Throws:
      IOException