netty解码器实例  
   
所属分类 netty
浏览量 394
解码字节到消息(ByteToMessageDecoder 和 ReplayingDecoder)
解码消息到消息(MessageToMessageDecoder)
ByteToMessageDecoder的具体实现类包括 
LineBasedFrameDecoder 、 DelimiterBasedFrameDecoder 和 FixedLengthFrameDecoder 等
public class ToIntegerDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List< Object> out) throws Exception {
        // int是4字节
        if(in.readableBytes() > = 4) {   
            // 添加到解码信息的List中     
            out.add(in.readInt());            
        }
    } 
}
一个消息被编码或解码会自动调用 ReferenceCountUtil.release(message)
如果稍后还需要用到这个引用,可以调用 ReferenceCountUtil.retain(message)
ReplayingDecoder
使用 ReplayingDecoder 就无需检查要读取的字节数
若 ByteBuf 中有足够的字节,则会正常读取;若没有足够的字节则会停止解码
public class ToIntegerDecoder2 extends ReplayingDecoder< Void> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List< Object> out) throws Exception {
         out.add(in.readInt());  
    }     
}
public class IntegerToStringDecoder extends MessageToMessageDecoder< Integer> {
    @Override
    protected void decode(ChannelHandlerContext ctx, Integer msg, List< Object> out) throws Exception {
        out.add(String.valueOf(msg));    
    }
}
io.netty.handler.codec.string.StringDecoder
@Sharable
public class StringDecoder extends MessageToMessageDecoder< ByteBuf> {
    // TODO Use CharsetDecoder instead.
    private final Charset charset;
    // Creates a new instance with the current system character set.
    public StringDecoder() {
        this(Charset.defaultCharset());
    }
    // Creates a new instance with the specified character set.
    public StringDecoder(Charset charset) {
        this.charset = ObjectUtil.checkNotNull(charset, "charset");
    }
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List< Object> out) throws Exception {
        out.add(msg.toString(charset));
    }
}
io.netty.handler.codec.string.StringEncoder
@Sharable
public class StringEncoder extends MessageToMessageEncoder< CharSequence> {
    private final Charset charset;
    // Creates a new instance with the current system character set.
    public StringEncoder() {
        this(Charset.defaultCharset());
    }
    // Creates a new instance with the specified character set.
    public StringEncoder(Charset charset) {
        this.charset = ObjectUtil.checkNotNull(charset, "charset");
    }
    @Override
    protected void encode(ChannelHandlerContext ctx, CharSequence msg, List< Object> out) throws Exception {
        if (msg.length() == 0) {
            return;
        }
        out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(msg), charset));
    }
}
 上一篇  
   
 下一篇  
 netty学习资料汇总 
 netty ByteBuf 种类 
 netty ByteToMessageDecoder 
 Netty EventLoop 
 netty VS mina 
 热锅冷油,炒菜不粘锅的科学原理