Netty的ByteToMessageDecoder是一个比较特殊的ChannelHandler,他在整个pipeline中只能有一个,而且只能放在第一位。需要实现decode方法。
public class TestDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
Object decoded = decode(ctx, in);
if (decoded != null) {
out.add(decoded);
}
}
private Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
int readableBytes = in.readableBytes();
if (readableBytes < 4) {
return null;
}
// read会改变readerIndex,所以read之前做标记,如果不能读成功,将readerIndex还原
// in.markReaderIndex();
// int size = in.readInt();
// 或者采用get的方式读,这样readerIndex不会移动
int size = in.getInt(0);
if (size <= 0) {
// in.resetReaderIndex();
return null;
}
if (size > in.readableBytes()) {
// in.resetReaderIndex();
return null;
}
byte[] bytes = new byte[size];
// get方式readerIndex还是在初始位置,所以要跳过size的四个字节
in.skipBytes(4);
in.readBytes(bytes);
String json = new String(bytes, StandardCharsets.UTF_8);
log.info("TestDecoder decode json:{}", json);
return json;
}
}
in是原始的输入流,通常这是一个DirectByteBuf,如果docode的时候发现所需数据不足,则必须要直接返回,不能往out里加null对象,add方法会检测decoded对象不能为空;同时,为了让下一次有数据来到且数据充足的时候能完整地读到整个数据,必须将in的readerIndex重置到原始位置。
除非特殊需求要丢掉一些bytes,否则应该严格遵循一个原则:in读了多数bytes(readerIndex移动了多少),那么对应的out应该要输出多少对应的数据。
ByteToArrayDecoder在整个pipeline链路中只能有一个,它是处理原始字节流ByteBuf的,所以它一般是放在链路的第一位;即使你的一个ByteToMessageDecoder的输出任然是一个ByteBuf对象,你的pipeline的下一个channelHandler也不能是ByteToMessageDecoder,而必须要用MessageToMessageDecoder<ByteBuf>。这个可以参考内置的两个InboundChannelHandler
// Decoders
pipeline.addLast("frameDecoder",
new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
pipeline.addLast("bytesDecoder",
new ByteArrayDecoder());
附带官网关于ByteToMessageDecoder的说明: