I think you want to extend ByteToMessageDecoder and let it do the job of aggregation of needed. See the javadocs of it for more details.
Receiving larger bytebuffer Android
-
29-06-2022 - |
Question
I'm using the framework Netty with Android and having problems when I receive large amounts of data:
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) {
bufferIn = (ByteBuf) msg;
if (bufferIn.readableBytes() >= 4) {
size = bufferIn.readInt();
result = bufferIn.toString(CharsetUtil.ISO_8859_1);
if(size == result.length){
Log.d("D", "RECEIVED: " + size + " " + result);
}
ctx.flush();
}
bufferIn.release();
}
When I receive the data it comes in packets, and I'm not knowing how to receive that parcels. Thanks
I add the line:
ch.pipeline().addLast(new NettyDecoder(), new NettyHandler(service, size, message, listener));
On the decoder:
class NettyDecoder extends ByteToMessageDecoder
@Override protected void decode(final ChannelHandlerContext theContext, final ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() < 4) {
return;
}
in.markReaderIndex();
int dataLength = in.readInt();
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
return;
}
byte[] decoded = new byte[dataLength];
in.readBytes(decoded);
out.add(decoded);
//out.add(in.readBytes(in.readableBytes()));
}
On the handler:
void channelRead(final ChannelHandlerContext ctx, Object msg) {
ByteBuf m = (ByteBuf) msg;
bufferIn.writeBytes(m);
m.release();
if (bufferIn.readableBytes() >= 4) {
size = bufferIn.readInt();
for (int i = 0; i < bufferIn.capacity(); i ++) {
byte b = bufferIn.getByte(i);
result += (char) b;
}
}
Log.d("WEB", "RESULT: " + size + " " + result.getBytes().length + " " + result);
bufferIn.release();
But now I don't receive any message on the NettyHandler.
Can someone teachs me how to receive the messages on the handler?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow