1

I'm extending ChannelInboundHandlerAdapter and would like to read the exact number of bytes.

public class Reader extends ChannelInboundHandlerAdapter{ @Override public void channelRead(ChannelHandlerContext ctx, Object msg){ ByteBuf b = (ByteBuf) msg; byte size = b.readByte(); //Now I want to read exactly size bytes from the channel //and then again read the number of bytes and read the bytes... } } 

The issue is it may happen that we read less then required bytes from ByteBuf. How to read more from the Channel?

1 Answer 1

2

Just for reading you may use b.readSlice(size). However, as you mentioned, the buffer may have not enough data yet for your message. So you need to consume data fully before creating the message. For that case, I would recommend you to use built-in ByteToMessageDecoder handler. It will handle low-level bytes for you. So with ByteToMessageDecoder your code will look like this:

class Reader extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { byte size = in.readByte(); if (in.readableBytes() < size) { in.resetReaderIndex(); return; } ByteBuf bb = in.readSlice(size); //make whatever you want with bb Message message = ...; out.add(message); } } 

So in this example, you read the number of bytes you need to read for the message - size. Then you check if your in buffer has enough data to consume. If not - you return control to ByteToMessageDecoder until it read more. And repeat, until you have enough data to construct your message.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, yes. Thanks a lot. But what about the differences between ReplayingDecoder? When to use which one?
@St.Antario please have a look at ReplayingDecoder javadocs. It has a very good explanation with examples. Briefly - ReplayingDecoder does more and you don't need to check in.readableBytes() < size. However, the price is - lower performance.
ReplayingDecoder can help you deal with complex situation of underlying stream data, e.g. data is not enough. If you don't care too much about performance, it will reduce your code logic complex too much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.