简述
分类入栈处理器(channelInboundHandler)&出栈处理器(channelOutboundHandler)
里面全都是回调方法,方法被触发的时候,会调用对应的实现。常见的编解码器有encode&decode
netty自定义处理器「常用的编解码器 ReplayingDecoder 2 -> ByteToMessageDecoder 1」
1使用的时候需要判断下 输入字节流是否满足需要转化类型的长度,自己需要去实现他如下图。2是1的子类 做了优化。
public class IntegerHeaderFrameDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx,
ByteBuf buf, List<Object> out) throws Exception {
//检测可读内容是否有4个字节,起码要有一个int
if (buf.readableBytes() < 4) {
return;
}
//为了回退使用
buf.markReaderIndex();
//读取头部记录的长度
int length = buf.readInt();
//如果主体记录的消息没来全 回退
if (buf.readableBytes() < length) {
buf.resetReaderIndex();
return;
}
//理想情况 全部读取
out.add(buf.readBytes(length));
}
}
is simplified like the following with ReplayingDecoder:
public class IntegerHeaderFrameDecoder
extends ReplayingDecoder<Void> {
protected void decode(ChannelHandlerContext ctx,
ByteBuf buf) throws Exception {
out.add(buf.readBytes(buf.readInt()));
}
}
replayingDecoder的弊端是如果网络传输慢,会重读读之前的数据