Burhan Ul Haqq Zahir
Burhan Ul Haqq Zahir

Reputation: 334

netty: how to get complete message from client

my code is like this on server side in handler class

package nettyechoserver;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

/**
* Handler implementation for the echo server.
*/

@Sharable
public class EchoServerHandler extends ChannelHandlerAdapter {
int i = 0;
ByteBuf in = null;
byte[] inByteBuf=new byte[78231];
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    in = ctx.alloc().buffer(4); // (1)
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
   in = (ByteBuf) msg;
    try {
        while (in.isReadable()) { // (1)

            inByteBuf[i] = in.readByte();

            System.out.flush();
            i++;
        }
    } finally {
        ReferenceCountUtil.release(msg); // (2)
    }
}

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
    final ByteBuf time = ctx.alloc().buffer(4);
   System.out.println("total read: " + i);
   String s = "Message Received";
        time.writeBytes(s.getBytes());
        final ChannelFuture f = ctx.writeAndFlush(time); // (3)
        f.addListener(new ChannelFutureListener() {

            public void operationComplete(ChannelFuture future) {
                assert f == future;
                ctx.close();
            }
        });
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    // Close the connection when an exception is raised.
    cause.printStackTrace();
    ctx.close();
}
}

now the problem is that I am sending 76 kb data in byte form and total received data size is 16 kb only other data is lost each time can any one help me to receive my whole data I am waiting for your answer

Upvotes: 1

Views: 1316

Answers (1)

Frederic Brégier
Frederic Brégier

Reputation: 2206

What happens here is that you receive a first block (TCP/IP way, cutting in several parts one big frame), but you handle only the first packet, not the following (and you should receive the others just after).

You should use some decoder that fits your needs, one decoder that will keep information packet after packet, until you get all needed information to pass to the next handler which will be your business one.

For instance, you could use LengthFieldBasedFrameDecoder, or simplest as FixedLengthFrameDecoder.

Upvotes: 1

Related Questions