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

精彩链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。

发表评论

返回顶部暗黑模式