0

I have the following code for my framedecoder:

protected Object decode(ChannelHandlerContext channelHandlerContext,
        Channel channel, ChannelBuffer channelBuffer) throws Exception {

    //Header 1 + 4 length bytes
    if (channelBuffer.readableBytes() < 5) {
        return null;
    }
    System.out.println(channelBuffer.readerIndex());

    //mark the reader index
    channelBuffer.markReaderIndex();

    //extract the length bytes and convert to an int value 
    //**note: length value of the message is a decimal not hex
    StringBuilder lengthBuilder = new StringBuilder("");
    for (int ctr = 1; ctr < 5; ctr += 1) {
        lengthBuilder.append(String.format("%02x",
                channelBuffer.getByte(ctr)));
    }
    int length = Integer.parseInt(hexToASCII(lengthBuilder.toString()));
    System.out.println("This is the length: " + length);
    System.out.println("reader index: " + channelBuffer.readerIndex());
            channelBuffer.readerIndex(4);

    //get the remaining bytes
    if (channelBuffer.readableBytes() <= length) {
        channelBuffer.resetReaderIndex();
        return null;
    }

    String s = "";
    for (int ctr = 0; ctr < length + 5; ctr += 1) {
        s += (char) channelBuffer.getByte(ctr);
    }

    return s;
}

everything's going fine until the int length = Integer.parseInt(hexToASCII(lengthBuilder.toString())); line. After that line, the decoder can still read the remaining bytes but it is now using the actual message as the length field generating a parse exception error.

Say, i have a message B0005EHELLO where [B is the header] [0005 - actual message length] [E - header 2] [HELLO - actual message].. After parsing the length field to an integer value, the decoder uses the first four letters of the actual message HELL to parse the length field and an exception was being produced. Kindly help me with this issue.

kaze
  • 1
  • 2

1 Answers1

0

Fixed by changing the readerIndex from 4 to 5.

channelBuffer.readerIndex(4);

I also added a reader index reset before returning the result so that it would read the whole message not just the actual message :)

channelBuffer.readerIndex(0);
String s = "";
for (int ctr = 0; ctr < length + 5; ctr += 1) {
    s += (char) channelBuffer.getByte(ctr);
}
kaze
  • 1
  • 2