Class ByteToMessageDecoder
- All Implemented Interfaces:
io.netty.channel.ChannelHandler,io.netty.channel.ChannelInboundHandler
- Direct Known Subclasses:
BrotliDecoder,Bzip2Decoder,DelimiterBasedFrameDecoder,FastLzFrameDecoder,FixedLengthFrameDecoder,JsonObjectDecoder,LengthFieldBasedFrameDecoder,LineBasedFrameDecoder,Lz4FrameDecoder,LzfDecoder,ProtobufVarint32FrameDecoder,ReplayingDecoder,SnappyFrameDecoder,XmlFrameDecoder,ZlibDecoder
ChannelInboundHandlerAdapter which decodes bytes in a stream-like fashion from one ByteBuf to an
other Message type.
For example here is an implementation which reads all readable bytes from
the input ByteBuf and create a new ByteBuf.
public class SquareDecoder extends ByteToMessageDecoder {
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
throws Exception {
out.add(in.readBytes(in.readableBytes()));
}
}
Frame detection
Generally frame detection should be handled earlier in the pipeline by adding a
DelimiterBasedFrameDecoder, FixedLengthFrameDecoder, LengthFieldBasedFrameDecoder,
or LineBasedFrameDecoder.
If a custom frame decoder is required, then one needs to be careful when implementing
one with ByteToMessageDecoder. Ensure there are enough bytes in the buffer for a
complete frame by checking ByteBuf.readableBytes(). If there are not enough bytes
for a complete frame, return without modifying the reader index to allow more bytes to arrive.
To check for complete frames without modifying the reader index, use methods like ByteBuf.getInt(int).
One MUST use the reader index when using methods like ByteBuf.getInt(int).
For example calling in.getInt(0) is assuming the frame starts at the beginning of the buffer, which
is not always the case. Use in.getInt(in.readerIndex()) instead.
Pitfalls
Be aware that sub-classes of ByteToMessageDecoder MUST NOT
annotated with
invalid @link
{@link @Sharable
Some methods such as ByteBuf.readBytes(int) will cause a memory leak if the returned buffer
is not released or added to the out List. Use derived buffers like ByteBuf.readSlice(int)
to avoid leaking memory.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceCumulateByteBufs.Nested classes/interfaces inherited from interface io.netty.channel.ChannelHandler
io.netty.channel.ChannelHandler.Sharable -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final ByteToMessageDecoder.CumulatorCumulateByteBufs by add them to aCompositeByteBufand so do no memory copy whenever possible.static final ByteToMessageDecoder.CumulatorCumulateByteBufs by merge them into oneByteBuf's, using memory copies. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected intReturns the actual number of readable bytes in the internal cumulative buffer of this decoder.protected voidcallDecode(io.netty.channel.ChannelHandlerContext ctx, io.netty.buffer.ByteBuf in, List<Object> out) Called once data should be decoded from the givenByteBuf.voidchannelInactive(io.netty.channel.ChannelHandlerContext ctx) voidchannelRead(io.netty.channel.ChannelHandlerContext ctx, Object msg) voidchannelReadComplete(io.netty.channel.ChannelHandlerContext ctx) protected abstract voidDecode the from oneByteBufto an other.protected voiddecodeLast(io.netty.channel.ChannelHandlerContext ctx, io.netty.buffer.ByteBuf in, List<Object> out) Is called one last time when theChannelHandlerContextgoes in-active.protected final voidfinal voidhandlerRemoved(io.netty.channel.ChannelHandlerContext ctx) protected voidhandlerRemoved0(io.netty.channel.ChannelHandlerContext ctx) Gets called after theByteToMessageDecoderwas removed from the actual context and it doesn't handle events anymore.protected io.netty.buffer.ByteBufReturns the internal cumulative buffer of this decoder.booleanIftruethen only one message is decoded on eachchannelRead(ChannelHandlerContext, Object)call.voidsetCumulator(ByteToMessageDecoder.Cumulator cumulator) Set theByteToMessageDecoder.Cumulatorto use for cumulate the receivedByteBufs.voidsetDiscardAfterReads(int discardAfterReads) Set the number of reads after whichByteBuf.discardSomeReadBytes()are called and so free up memory.voidsetSingleDecode(boolean singleDecode) If set then only one message is decoded on eachchannelRead(ChannelHandlerContext, Object)call.voiduserEventTriggered(io.netty.channel.ChannelHandlerContext ctx, Object evt) Methods inherited from class io.netty.channel.ChannelInboundHandlerAdapter
channelActive, channelRegistered, channelUnregistered, channelWritabilityChanged, exceptionCaughtMethods inherited from class io.netty.channel.ChannelHandlerAdapter
ensureNotSharable, handlerAdded, isSharableMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface io.netty.channel.ChannelHandler
handlerAdded
-
Field Details
-
MERGE_CUMULATOR
CumulateByteBufs by merge them into oneByteBuf's, using memory copies. -
COMPOSITE_CUMULATOR
CumulateByteBufs by add them to aCompositeByteBufand so do no memory copy whenever possible. Be aware thatCompositeByteBufuse a more complex indexing implementation so depending on your use-case and the decoder implementation this may be slower than just use theMERGE_CUMULATOR.
-
-
Constructor Details
-
ByteToMessageDecoder
protected ByteToMessageDecoder()
-
-
Method Details
-
setSingleDecode
public void setSingleDecode(boolean singleDecode) If set then only one message is decoded on eachchannelRead(ChannelHandlerContext, Object)call. This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up. Default isfalseas this has performance impacts. -
isSingleDecode
public boolean isSingleDecode()Iftruethen only one message is decoded on eachchannelRead(ChannelHandlerContext, Object)call. Default isfalseas this has performance impacts. -
setCumulator
Set theByteToMessageDecoder.Cumulatorto use for cumulate the receivedByteBufs. -
setDiscardAfterReads
public void setDiscardAfterReads(int discardAfterReads) Set the number of reads after whichByteBuf.discardSomeReadBytes()are called and so free up memory. The default is16. -
actualReadableBytes
protected int actualReadableBytes()Returns the actual number of readable bytes in the internal cumulative buffer of this decoder. You usually do not need to rely on this value to write a decoder. Use it only when you must use it at your own risk. This method is a shortcut tointernalBuffer().readableBytes(). -
internalBuffer
protected io.netty.buffer.ByteBuf internalBuffer()Returns the internal cumulative buffer of this decoder. You usually do not need to access the internal buffer directly to write a decoder. Use it only when you must use it at your own risk. -
handlerRemoved
- Specified by:
handlerRemovedin interfaceio.netty.channel.ChannelHandler- Overrides:
handlerRemovedin classio.netty.channel.ChannelHandlerAdapter- Throws:
Exception
-
handlerRemoved0
Gets called after theByteToMessageDecoderwas removed from the actual context and it doesn't handle events anymore.- Throws:
Exception
-
channelRead
- Specified by:
channelReadin interfaceio.netty.channel.ChannelInboundHandler- Overrides:
channelReadin classio.netty.channel.ChannelInboundHandlerAdapter- Throws:
Exception
-
channelReadComplete
- Specified by:
channelReadCompletein interfaceio.netty.channel.ChannelInboundHandler- Overrides:
channelReadCompletein classio.netty.channel.ChannelInboundHandlerAdapter- Throws:
Exception
-
discardSomeReadBytes
protected final void discardSomeReadBytes() -
channelInactive
- Specified by:
channelInactivein interfaceio.netty.channel.ChannelInboundHandler- Overrides:
channelInactivein classio.netty.channel.ChannelInboundHandlerAdapter- Throws:
Exception
-
userEventTriggered
public void userEventTriggered(io.netty.channel.ChannelHandlerContext ctx, Object evt) throws Exception - Specified by:
userEventTriggeredin interfaceio.netty.channel.ChannelInboundHandler- Overrides:
userEventTriggeredin classio.netty.channel.ChannelInboundHandlerAdapter- Throws:
Exception
-
callDecode
protected void callDecode(io.netty.channel.ChannelHandlerContext ctx, io.netty.buffer.ByteBuf in, List<Object> out) Called once data should be decoded from the givenByteBuf. This method will calldecode(ChannelHandlerContext, ByteBuf, List)as long as decoding should take place.- Parameters:
ctx- theChannelHandlerContextwhich thisByteToMessageDecoderbelongs toin- theByteBuffrom which to read dataout- theListto which decoded messages should be added
-
decode
protected abstract void decode(io.netty.channel.ChannelHandlerContext ctx, io.netty.buffer.ByteBuf in, List<Object> out) throws Exception Decode the from oneByteBufto an other. This method will be called till either the inputByteBufhas nothing to read when return from this method or till nothing was read from the inputByteBuf.- Parameters:
ctx- theChannelHandlerContextwhich thisByteToMessageDecoderbelongs toin- theByteBuffrom which to read dataout- theListto which decoded messages should be added- Throws:
Exception- is thrown if an error occurs
-
decodeLast
protected void decodeLast(io.netty.channel.ChannelHandlerContext ctx, io.netty.buffer.ByteBuf in, List<Object> out) throws Exception Is called one last time when theChannelHandlerContextgoes in-active. Which means thechannelInactive(ChannelHandlerContext)was triggered. By default, this will just calldecode(ChannelHandlerContext, ByteBuf, List)but sub-classes may override this for some special cleanup operation.- Throws:
Exception
-