Netty入门(六)Decoder(解码器)
Netty 提供了丰富的解码器抽象基类,主要分为两类:
- 解码字节到消息(ByteToMessageDecoder 和 ReplayingDecoder)
- 解码消息到消息(MessageToMessageDecoder)
一、ByteToMessageDecoder
ByteToMessageDecoder 用于将字节转为信息(或其他字节序列)。方法如下:

在下面的例子中,我们将实现从入站 ByteBuf 读取每个整数并将其传递给 pipeline 中的下一个 ChannalInboundHandler。流程如下:

代码如下:
/**
* 读取四字节,解码成整形
* 继承于 ByteToMessageDecoder
*
*/
public class ToIntegerDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if(in.readableBytes() >= 4) { // int是4字节
out.add(in.readInt()); // 添加到解码信息的List中
}
}
}注意,一旦一个消息被编码或解码会自动调用 ReferenceCountUtil.release(message)。如果你稍后还需要用到这个引用,你可以调用 ReferenceCountUtil.retain(message)。
二、ReplayingDecoder
上面的例子读取缓冲区的数据之前需要检查缓冲区是否有足够的字节,使用 ReplayingDecoder 就无需自己检查。若 ByteBuf 中有足够的字节,则会正常读取;若没有足够的字节则会停止解码。如下:
/**
* 读取四字节,解码成整形
* 继承于ReplayingDecoder,不需要检查缓存区是否有足够的字节
*
*/
public class ToIntegerDecoder2 extends ReplayingDecoder<Void> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
out.add(in.readInt()); // 读取整形并添加到解码信息的List中
}
}三、MessageToMessageDecoder
用于从一种消息解码为另一种消息(例如,POJO 到 POJO)。与上面类似,代码如下:
/**
* 将整形解码为字符串
* 继承于MessageToMessageDecoder
*
*/
public class IntegerToStringDecoder extends MessageToMessageDecoder<Integer> {
@Override
protected void decode(ChannelHandlerContext ctx, Integer msg, List<Object> out) throws Exception {
out.add(String.valueOf(msg)); // 将整形转换为字符串
}
}四、在解码中处理太大的帧
Netty 是异步架构需要将缓冲区字节存在内存中,知道你能够解码它们。因此,你不能让你的解码器缓存太多的数据以免耗尽可用内存。下面为解决方案:
/**
* 在解码时处理太大的帧
*
*/
public class SafeByteToMessageDecoder extends ByteToMessageDecoder {
private static final int MAX_FRAME_SIZE = 1024;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
int readable = in.readableBytes();
if(readable > MAX_FRAME_SIZE) { // 缓冲区数据过大
in.skipBytes(readable); // 忽略所有可读的字节
// 抛出异常通知这个帧数据超长
throw new TooLongFrameException("帧数据超长");
}
// TODO 数据编码
}
}这种保护很重要,尤其是当你编码一个有可变帧大小的协议的时候。
相关推荐
fengshantao 2020-10-29
arctan0 2020-10-14
爱传文档 2020-07-28
gzx0 2020-07-05
fengshantao 2020-07-04
fengshantao 2020-07-02
jannal 2020-06-21
arctan0 2020-06-19
arctan0 2020-06-16
gzx0 2020-06-14
fengshantao 2020-06-13
gzx0 2020-06-12
arctan0 2020-06-11
fengshantao 2020-06-11
mbcsdn 2020-05-19
arctan0 2020-05-16
爱传文档 2020-05-08
爱传文档 2020-05-04