Frame a message with a four-byte big-endian length
Frame a message with a four-byte big-endian length
Answer
byte[] body = "PING 42".getBytes(StandardCharsets.UTF_8); ByteBuffer frame = ByteBuffer.allocate(4 + body.length); frame.putInt(body.length); frame.put(body); frame.flip();
putInt writes four bytes in the buffer default order, which is BIG_ENDIAN and therefore network byte order. The bulk put appends the payload, and flip() sets limit to 11 and position to 0 so the whole frame is ready to drain onto a channel.
Harold 4e ch11 §Creating Buffers; §Bulk Methods; §Data Conversion