netty源码分析 之十 codec

来源:互联网 发布:va ips 知乎 编辑:程序博客网 时间:2024/06/06 08:59

前面学习了别的handler,都是直接继承ChannelHandlerAdapter  或者间接继承来实现的。


codec也很简单,顾名思义 解遍码器


核心类有以下几个


ByteToMessageCodec

ByteBuf 与Object 之间的转换


重写了ChannelHandlerAdapter   的两个方法 channelRead writer


    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        decoder.channelRead(ctx, msg);    }    @Override    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {        encoder.write(ctx, msg, promise);    }


然后具体再有定义decoder和encoder来实现


ByteToMessageDecoder

之类来实现下,decode方法

/**     * Decode the from one {@link ByteBuf} to an other. This method will be called till either the input     * {@link ByteBuf} has nothing to read when return from this method or till nothing was read from the input     * {@link ByteBuf}.     *     * @param ctx           the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to     * @param in            the {@link ByteBuf} from which to read data     * @param out           the {@link List} to which decoded messages should be added     * @throws Exception    is thrown if an error accour     */    protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception;



MessageToByteEncoder

关注下encode即可

    /**     * Encode a message into a {@link ByteBuf}. This method will be called for each written message that can be handled     * by this encoder.     *     * @param ctx           the {@link ChannelHandlerContext} which this {@link MessageToByteEncoder} belongs to     * @param msg           the message to encode     * @param out           the {@link ByteBuf} into which the encoded message will be written     * @throws Exception    is thrown if an error accour     */    protected abstract void encode(ChannelHandlerContext ctx, I msg, ByteBuf out) throws Exception;


MessageToMessageCodec

Object与Object 之间进行转换

同上面的道理,这里留给读者自己学习吧。
0 0
原创粉丝点击