固定長度解碼器
For example, if you received the following four fragmented packets:
<pre>
+---+----+------+----+
| A | BC | DEFG | HI |
+---+----+------+----+
</pre>
A FixedLengthFrameDecoderwill decode them into the following three packets with the fixed length:
<pre>
+-----+-----+-----+
| ABC | DEF | GHI |
+-----+-----+-----+
解碼
protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
// 解碼
Object decoded = decode(ctx, in);
// 如果解碼成功,那么將返回結(jié)果添加到out中
if (decoded != null) {
out.add(decoded);
}
}
protected Object decode(
@SuppressWarnings("UnusedParameters") ChannelHandlerContext ctx, ByteBuf in) throws Exception {
// 如果沒有到達規(guī)定的定長,那么返回null
// 在ByteToMessageDecode那邊會認為沒有讀取任何數(shù)據(jù),直接結(jié)束循環(huán),等待下次讀取事件的到來
if (in.readableBytes() < frameLength) {
return null;
} else {
// 可見數(shù)據(jù)滿足要求, 截取定長的數(shù)據(jù)返回.
return in.readRetainedSlice(frameLength);
}
}
readRetainedSlice
// 這里實際上是生成源Buffer的只讀緩沖區(qū),且retain
public ByteBuf readRetainedSlice(int length) {
ByteBuf slice = retainedSlice(readerIndex, length);
readerIndex += length;
return slice;
}