Top Description Inners Fields Constructors Methods
io.netty.handler.codec

public abstract Class ByteToMessageDecoder

extends ChannelInboundHandlerAdapter
Class Inheritance
Known Direct Subclasses
io.netty.handler.codec.DelimiterBasedFrameDecoder, io.netty.handler.codec.FixedLengthFrameDecoder, io.netty.handler.codec.LengthFieldBasedFrameDecoder, io.netty.handler.codec.LineBasedFrameDecoder, io.netty.handler.codec.ReplayingDecoder, io.netty.handler.codec.compression.FastLzFrameDecoder, io.netty.handler.codec.compression.BrotliDecoder, io.netty.handler.codec.compression.Bzip2Decoder, io.netty.handler.codec.compression.Lz4FrameDecoder, io.netty.handler.codec.compression.LzfDecoder, io.netty.handler.codec.compression.SnappyFrameDecoder, io.netty.handler.codec.compression.ZlibDecoder, io.netty.handler.codec.json.JsonObjectDecoder, io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder, io.netty.handler.codec.xml.XmlFrameDecoder
Imports
io.netty.buffer.ByteBuf, .ByteBufAllocator, .CompositeByteBuf, .Unpooled, io.netty.channel.ChannelConfig, .ChannelHandlerContext, .ChannelInboundHandlerAdapter, io.netty.channel.socket.ChannelInputShutdownEvent, io.netty.util.IllegalReferenceCountException, io.netty.util.internal.ObjectUtil, .StringUtil, java.util.List

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 @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 and Inner Type Summary

Modifier and TypeClass and Description
public static interface

Field Summary

Modifier and TypeField and Description
public static final ByteToMessageDecoder.Cumulator
COMPOSITE_CUMULATOR

Cumulate ByteBufs by add them to a CompositeByteBuf and so do no memory copy whenever possible.

pack-priv ByteBuf
private ByteToMessageDecoder.Cumulator
private byte
private int
private boolean
firedChannelRead

This flag is used to determine if we need to call ChannelHandlerContext#read() to consume more data when ChannelConfig#isAutoRead() is false.

private boolean
public static final ByteToMessageDecoder.Cumulator
MERGE_CUMULATOR

Cumulate ByteBufs by merge them into one ByteBuf's, using memory copies.

private int
private boolean
private boolean
private static final byte
private static final byte
private static final byte

Constructor Summary

AccessConstructor and Description
protected

Method Summary

Modifier and TypeMethod and Description
protected int
actualReadableBytes()

Returns the actual number of readable bytes in the internal cumulative buffer of this decoder.

protected void
callDecode(ChannelHandlerContext ctx, ByteBuf
the ByteBuf from which to read data
in
,
List<Object>
the List to which decoded messages should be added
out
)

Called once data should be decoded from the given ByteBuf.

public void
private void
channelInputClosed(ChannelHandlerContext ctx, boolean callChannelInactive)

pack-priv void
channelInputClosed(ChannelHandlerContext ctx, List<Object> out)

Called when the input of the channel was closed which may be because it changed to inactive or because of ChannelInputShutdownEvent.

public void
public void
protected abstract void
decode(ChannelHandlerContext ctx, ByteBuf
the ByteBuf from which to read data
in
,
List<Object>
the List to which decoded messages should be added
out
)

Decode the from one ByteBuf to an other.

protected void
decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)

Is called one last time when the ChannelHandlerContext goes in-active.

pack-priv final void
decodeRemovalReentryProtection(ChannelHandlerContext ctx, ByteBuf
the ByteBuf from which to read data
in
,
List<Object>
the List to which decoded messages should be added
out
)

Decode the from one ByteBuf to an other.

protected final void
pack-priv static ByteBuf
pack-priv static void
fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements)

Get numElements out of the List and forward these through the pipeline.

pack-priv static void
fireChannelRead(ChannelHandlerContext ctx, CodecOutputList msgs, int numElements)

Get numElements out of the CodecOutputList and forward these through the pipeline.

public final void
handlerRemoved(ChannelHandlerContext ctx)

Overrides io.netty.channel.ChannelHandlerAdapter.handlerRemoved.

Implements io.netty.channel.ChannelHandler.handlerRemoved.

Gets called after the ChannelHandler was removed from the actual context and it doesn't handle events anymore.
protected void
handlerRemoved0(ChannelHandlerContext ctx)

Gets called after the ByteToMessageDecoder was removed from the actual context and it doesn't handle events anymore.

protected ByteBuf
internalBuffer()

Returns the internal cumulative buffer of this decoder.

public boolean
isSingleDecode()

If true then only one message is decoded on each channelRead(ChannelHandlerContext, Object) call.

public void
setCumulator(ByteToMessageDecoder.Cumulator cumulator)

Set the Cumulator to use for cumulate the received ByteBufs.

public void
setDiscardAfterReads(int discardAfterReads)

Set the number of reads after which ByteBuf#discardSomeReadBytes() are called and so free up memory.

public void
setSingleDecode(boolean singleDecode)

If set then only one message is decoded on each channelRead(ChannelHandlerContext, Object) call.

public void
Inherited from io.netty.channel.ChannelInboundHandlerAdapter:
channelActivechannelRegisteredchannelUnregisteredchannelWritabilityChangedexceptionCaught

Field Detail

COMPOSITE_CUMULATORback to summary
public static final ByteToMessageDecoder.Cumulator COMPOSITE_CUMULATOR

Cumulate ByteBufs by add them to a CompositeByteBuf and so do no memory copy whenever possible. Be aware that CompositeByteBuf use a more complex indexing implementation so depending on your use-case and the decoder implementation this may be slower than just use the MERGE_CUMULATOR.

cumulationback to summary
pack-priv ByteBuf cumulation
cumulatorback to summary
private ByteToMessageDecoder.Cumulator cumulator
decodeStateback to summary
private byte decodeState

A bitmask where the bits are defined as

discardAfterReadsback to summary
private int discardAfterReads
firedChannelReadback to summary
private boolean firedChannelRead

This flag is used to determine if we need to call ChannelHandlerContext#read() to consume more data when ChannelConfig#isAutoRead() is false.

firstback to summary
private boolean first
MERGE_CUMULATORback to summary
public static final ByteToMessageDecoder.Cumulator MERGE_CUMULATOR

Cumulate ByteBufs by merge them into one ByteBuf's, using memory copies.

numReadsback to summary
private int numReads
selfFiredChannelReadback to summary
private boolean selfFiredChannelRead
singleDecodeback to summary
private boolean singleDecode
STATE_CALLING_CHILD_DECODEback to summary
private static final byte STATE_CALLING_CHILD_DECODE
STATE_HANDLER_REMOVED_PENDINGback to summary
private static final byte STATE_HANDLER_REMOVED_PENDING
STATE_INITback to summary
private static final byte STATE_INIT

Constructor Detail

ByteToMessageDecoderback to summary
protected ByteToMessageDecoder()

Method Detail

actualReadableBytesback to summary
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 to internalBuffer().readableBytes().

callDecodeback to summary
protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)

Called once data should be decoded from the given ByteBuf. This method will call decode(ChannelHandlerContext, ByteBuf, List) as long as decoding should take place.

Parameters
ctx:ChannelHandlerContext

the ChannelHandlerContext which this ByteToMessageDecoder belongs to

in:ByteBuf

the ByteBuf from which to read data

out:List<Object>

the List to which decoded messages should be added

channelInactiveback to summary
public void channelInactive(ChannelHandlerContext ctx) throws Exception

Overrides io.netty.channel.ChannelInboundHandlerAdapter.channelInactive.

Implements io.netty.channel.ChannelInboundHandler.channelInactive.

Doc from io.netty.channel.ChannelInboundHandlerAdapter.channelInactive.

Calls ChannelHandlerContext#fireChannelInactive() to forward to the next ChannelInboundHandler in the ChannelPipeline. Sub-classes may override this method to change behavior.

Annotations
@Override
channelInputClosedback to summary
private void channelInputClosed(ChannelHandlerContext ctx, boolean callChannelInactive)
channelInputClosedback to summary
pack-priv void channelInputClosed(ChannelHandlerContext ctx, List<Object> out) throws Exception

Called when the input of the channel was closed which may be because it changed to inactive or because of ChannelInputShutdownEvent.

channelReadback to summary
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception

Overrides io.netty.channel.ChannelInboundHandlerAdapter.channelRead.

Implements io.netty.channel.ChannelInboundHandler.channelRead.

Doc from io.netty.channel.ChannelInboundHandlerAdapter.channelRead.

Calls ChannelHandlerContext#fireChannelRead(Object) to forward to the next ChannelInboundHandler in the ChannelPipeline. Sub-classes may override this method to change behavior.

Annotations
@Override
channelReadCompleteback to summary
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception

Overrides io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete.

Implements io.netty.channel.ChannelInboundHandler.channelReadComplete.

Doc from io.netty.channel.ChannelInboundHandlerAdapter.channelReadComplete.

Calls ChannelHandlerContext#fireChannelReadComplete() to forward to the next ChannelInboundHandler in the ChannelPipeline. Sub-classes may override this method to change behavior.

Annotations
@Override
decodeback to summary
protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception

Decode the from one ByteBuf to an other. This method will be called till either the input ByteBuf has nothing to read when return from this method or till nothing was read from the input ByteBuf.

Parameters
ctx:ChannelHandlerContext

the ChannelHandlerContext which this ByteToMessageDecoder belongs to

in:ByteBuf

the ByteBuf from which to read data

out:List<Object>

the List to which decoded messages should be added

Exceptions
Exception:
is thrown if an error occurs
decodeLastback to summary
protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception

Is called one last time when the ChannelHandlerContext goes in-active. Which means the channelInactive(ChannelHandlerContext) was triggered. By default, this will just call decode(ChannelHandlerContext, ByteBuf, List) but sub-classes may override this for some special cleanup operation.

decodeRemovalReentryProtectionback to summary
pack-priv final void decodeRemovalReentryProtection(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception

Decode the from one ByteBuf to an other. This method will be called till either the input ByteBuf has nothing to read when return from this method or till nothing was read from the input ByteBuf.

Parameters
ctx:ChannelHandlerContext

the ChannelHandlerContext which this ByteToMessageDecoder belongs to

in:ByteBuf

the ByteBuf from which to read data

out:List<Object>

the List to which decoded messages should be added

Exceptions
Exception:
is thrown if an error occurs
discardSomeReadBytesback to summary
protected final void discardSomeReadBytes()
expandCumulationback to summary
pack-priv static ByteBuf expandCumulation(ByteBufAllocator alloc, ByteBuf oldCumulation, ByteBuf in)
fireChannelReadback to summary
pack-priv static void fireChannelRead(ChannelHandlerContext ctx, List<Object> msgs, int numElements)

Get numElements out of the List and forward these through the pipeline.

fireChannelReadback to summary
pack-priv static void fireChannelRead(ChannelHandlerContext ctx, CodecOutputList msgs, int numElements)

Get numElements out of the CodecOutputList and forward these through the pipeline.

handlerRemovedback to summary
public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception

Overrides io.netty.channel.ChannelHandlerAdapter.handlerRemoved.

Implements io.netty.channel.ChannelHandler.handlerRemoved.

Doc from io.netty.channel.ChannelHandler.handlerRemoved.

Gets called after the ChannelHandler was removed from the actual context and it doesn't handle events anymore.

Annotations
@Override
handlerRemoved0back to summary
protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception

Gets called after the ByteToMessageDecoder was removed from the actual context and it doesn't handle events anymore.

internalBufferback to summary
protected 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.

isSingleDecodeback to summary
public boolean isSingleDecode()

If true then only one message is decoded on each channelRead(ChannelHandlerContext, Object) call. Default is false as this has performance impacts.

setCumulatorback to summary
public void setCumulator(ByteToMessageDecoder.Cumulator cumulator)

Set the Cumulator to use for cumulate the received ByteBufs.

setDiscardAfterReadsback to summary
public void setDiscardAfterReads(int discardAfterReads)

Set the number of reads after which ByteBuf#discardSomeReadBytes() are called and so free up memory. The default is 16.

setSingleDecodeback to summary
public void setSingleDecode(boolean singleDecode)

If set then only one message is decoded on each channelRead(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 is false as this has performance impacts.

userEventTriggeredback to summary
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception

Overrides io.netty.channel.ChannelInboundHandlerAdapter.userEventTriggered.

Implements io.netty.channel.ChannelInboundHandler.userEventTriggered.

Doc from io.netty.channel.ChannelInboundHandlerAdapter.userEventTriggered.

Calls ChannelHandlerContext#fireUserEventTriggered(Object) to forward to the next ChannelInboundHandler in the ChannelPipeline. Sub-classes may override this method to change behavior.

Annotations
@Override
io.netty.handler.codec back to summary

public Interface ByteToMessageDecoder.Cumulator


Cumulate ByteBufs.

Method Summary

Modifier and TypeMethod and Description
public ByteBuf
cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in)

Cumulate the given ByteBufs and return the ByteBuf that holds the cumulated bytes.

Method Detail

cumulateback to summary
public ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in)

Cumulate the given ByteBufs and return the ByteBuf that holds the cumulated bytes. The implementation is responsible to correctly handle the life-cycle of the given ByteBufs and so call ByteBuf#release() if a ByteBuf is fully consumed.