@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { if (buf.readableBytes() < 10) { return null; } int beginIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), new StringFinder("$$")); if (beginIndex == -1) { return null; } else if (beginIndex > buf.readerIndex()) { buf.readerIndex(beginIndex); } int length; int flagIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), new StringFinder("AA")); if (flagIndex != -1 && flagIndex - beginIndex == 6) { length = Integer.parseInt(buf.toString(buf.readerIndex() + 2, 4, Charset.defaultCharset())); } else { length = Integer.parseInt(buf.toString(buf.readerIndex() + 2, 2, Charset.defaultCharset()), 16); } if (length <= buf.readableBytes()) { return buf.readBytes(length); } return null; }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { char marker = (char) buf.getByte(buf.readerIndex()); while (marker != '*' && marker != '$' && buf.readableBytes() > 0) { buf.skipBytes(1); if (buf.readableBytes() > 0) { marker = (char) buf.getByte(buf.readerIndex()); } } if (marker == '*') { // Return text message int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) '#'); if (index != -1) { return buf.readBytes(index + 1 - buf.readerIndex()); } } else if (marker == '$' && buf.readableBytes() >= MESSAGE_LENGTH) { // Return binary message return buf.readBytes(MESSAGE_LENGTH); } return null; }
private static String readString(ChannelBuffer buf) { String result = null; int index = buf.indexOf(buf.readerIndex(), buf.writerIndex(), (byte) 0); if (index > buf.readerIndex()) { result = buf.readBytes(index - buf.readerIndex()).toString(StandardCharsets.US_ASCII); } buf.readByte(); return result; }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { ChannelBuffer result = (ChannelBuffer) super.decode(ctx, channel, buf); if (result != null) { int index = result.indexOf(result.readerIndex(), result.writerIndex(), (byte) '$'); if (index == -1) { return result; } else { result.skipBytes(index); return result.readBytes(result.readableBytes()); } } return null; }