netty源码:(40)ReplayingDecoder

netty源码:(40)ReplayingDecoder_第1张图片

ReplayingDecoder是ByteToMessageDecoder的子类,我们继承这个类时,也要实现decode方法,示例如下:

package cn.edu.tju;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.nio.charset.Charset;
import java.util.List;

public class MyLongReplayingDecoder extends ReplayingDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {

        int readIndex = in.readerIndex();
        int writerIndex = in.writerIndex();

        int readableBytes = in.readableBytes();
        long result = in.readLong();
        
        out.add(result);
    }
}


在从in中读取数据(readLong)时,不需要判断所读取的字节是否够用,不会报错,会等到字节够用了才返回。
netty源码:(40)ReplayingDecoder_第2张图片
上述代码用两种方式读取一条消息,消息分为消息头(定义消息体的长度)和消息体两部分。
第一种方式是使用普通的ByteToMessageDecoder,需要在读取之前判断ByteBuf中是否有足够的字节。
第二种方式使用ReplayingDecoder,读取之前不需要判断ByteBuf中是否有足够的字节,具体的实现原理是:当要读的字节不够时,抛出一个错误,捕获这个错误的时候重置readerIndex,然后进行下一次尝试,实质上就是一种重试机制。

你可能感兴趣的:(Netty,java)