8

When writing 2048bytes in on handler, the messageRevieved method should be called twice to receive the all data... how I can receive the 2048bytes data in

Code

Server:

public class Server{
    public static void main(String[] args){
        ChannelFactory factory=new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
        ServerBootstrap bootstrap=new ServerBootstrap(factory);
        bootstrap.setPipelineFactory(new CarPipelineFactory());

        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);

        bootstrap.bind(new InetSocketAddress(8989));
    }
}

Server Handler:

public class ServerHandler extends SimpleChannelHandler{

    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e){
        byte[] resp=data.getBytes();//data is a String greater than 1024bytes;
        ChannelBuffer buffer=ChannelBuffers.buffer(resp.length);
        buffer.writerBytes(resp);
        e.getChannel().write(buffer);
        buffer.clear();
    }
}

Client:

public class Client{
    public static void main(String[] args){
        ChannelFactory channelFactory=new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
        ClientBootstrap bootstrap=new ClientBootstrap(channelFactory);
        bootstrap.getPipeline().addLast("handler", new PhoneClientHandler());

        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);

        bootstrap.connect(new InetSocketAddress("127.0.0.1",8181));
    }
}

Client Handler:

public class ClientHandler extends SimpleChannelHandler{
    public void messageRecieved(ChannelHandlerContext ctx, ChannelStateEvent e){
        ChannelBuffer buffer=(ChannelBuffer)e.getMessage();
        int size=buffer.readableBytes();
        byte[] bytes=new byte[size];
        buffer.readBytes(bytes);
        buffer.clear();
        System.out.println(new String(bytes));//if the data size>1024,the String will speprate into parts.
    }
}
2
  • Sorry I don't understand the question. Can you try to be more specific ? Apr 16, 2012 at 8:22
  • i'am sorry,i'am a chinese and my english is not good. below is my question: as i'm using netty,when i write 2048bytes(any bigger than 1024bytes) data from one hand to another,the recieving hand should recieve twice,how i can revieve the whole data(bigger than 1024bytes) by once?
    – Gofier
    Apr 17, 2012 at 10:41

6 Answers 6

6

Well you can always decide how many bytes to write at a time, but you definitely never know when and how many bytes are received (this is why NIO makes sense). You need to handle you own buffer for receiving a fix number of bytes you want. To do so you can use a FrameDecoder which is design for this purpose.

Additionaly, you can make sure the datas does not stay too long in the sender socket buffer by setting tcpNoDelay to true, so it will no wait for the current "frame" to reach a certain critical size before physically sending the datas.

If I understand well, you are writing let's say 2048 Bytes in one hand but all the datas are not received in the messagedReceived event on the other hand? Try to check these common issues:

  • you application terminates too early and the datas are not yet arrived
  • your datas are stucked in the socket buffer of the "sender" because you did not close the Channel and tcpNoDelay option was not set to true. This is causing the socket to wait for some additional bytes before sending the packet.
  • you did not read all the datas inside the ChannelBuffer but for a reason the readerIndex as been set to a further position

Try to show us some part of your code, it should make things easier...

ADDED 17/04/2012

If I understand you are trying to pass a byte array coding for a String from the sender to the receiver. Here is your code after a littel refactor:

----------------------------code ----------------------------write hand: response.size()>1024bytes

byte[] datas = ((String)msg).getBytes("UTF-8"); //ALWAYS SPECIFY THE ENCODING
ChannelBuffer buffer = ChannelBuffers.wrap(datas); //USE DIRECTLY THE ARRAY
System.out.println(buffer);    //buffer'size>1024 here
channel.write(buffer);

----------------------------recieve hand: should recieve twice,println() would execute twice

ChannelBuffer buffer = (ChannelBuffer) event.getMessage(); 
System.out.println(buffer)    //buffer'size once 1024,once the remainder size
byte[] datas =buffer.readBytes(buffer.readableBytes()).array()
String msg=new String(datas , "UTF-8"); //BAD IDEA because the bytes sequence of the last UTF-8 char could be uncompleted there
System.out.println(str);

This is not the way to do that, you should instead use directly the StringEncoder and StringDecoder in the package org.jboss.netty.handler.codec.string. It will handle the Framing problem for you. If you still want to debug your code, use the LoggingHandler provided by Netty. Also did you really set this option:

bootstrap.setOption("tcpNoDelay", true);

in both sides bootstraps?

5
  • first of all,thank you for answering my question, I'am so sorry my english is not very good.yes,like you said,when i writing 2048bytes in on handler,the messageRevieved method should be called twice to recieve the all data...I will show my code right now,thank you agian.
    – Gofier
    Apr 17, 2012 at 5:12
  • really thank you! NumRenaud,i changed my code as you suggested,but the problem is still on,i am sure i set the option bootstrap.setOption("tcpNoDelay",true) in both sides,i also tried "child.tcpNoDelay",and i use "SimpleChannelHandler" in both side.
    – Gofier
    Apr 17, 2012 at 11:00
  • bootstrap.setOption("tcpNoDelay",true) in the client and bootstrap.setOption("child.tcpNoDelay",true) in the server
    – Renaud
    Apr 17, 2012 at 12:32
  • Cannot help you more with this little information you give... you'll have to put the whole code for your Handler and your BootStrap to reproduce the problem!
    – Renaud
    Apr 17, 2012 at 12:34
  • thank you for making attention to my question,I had pin my whole code above,expect for your awnser,thank you very much!
    – Gofier
    Apr 18, 2012 at 6:29
3

Try with TruncatedChannelBuffer or BigEndianHeapChannelBuffer instead of channelbuffer in your ClientHandler. I think it will work.. or if it doesn't work, kindly post stacktrace of generated exception. I tried this in my code and it worked..I hope this will help you.

public void messageReceived(ChannelHandlerContext channelHandlerContext,MessageEvent messageEvent) throws Exception {

    Object messageObject = messageEvent.getMessage();

    // if size of message < 1024 then TruncatedChannelBuffer is returned.

    if (messageObject instanceof TruncatedChannelBuffer) {

        try {

            TruncatedChannelBuffer truncatedChannelBuffer = (TruncatedChannelBuffer) messageObject;

            byte[] byteArray = new byte[truncatedChannelBuffer.readableBytes()];

            truncatedChannelBuffer.readBytes(byteArray);

            System.out.print(" Message = "+new String(byteArray));

            truncatedChannelBuffer.clear();

        } catch (Exception e) {

            System.out.println("Exception in MessageReceived...");

            e.printStackTrace();


        }
    }
    // if size of message > 1024 then BigEndianHeapChannelBuffer is returned.

    if (messageObject instanceof BigEndianHeapChannelBuffer) {

        try {

            BigEndianHeapChannelBuffer bigEndianHeapChannelBuffer = (BigEndianHeapChannelBuffer) messageObject;

            byte[] byteArray  = new byte[bigEndianHeapChannelBuffer.readableBytes()];

            bigEndianHeapChannelBuffer.readBytes(byteArray);

            System.out.print(" Message = "+new String(byteArray));

            bigEndianHeapChannelBuffer.clear();


        } catch (Exception e) {

            System.out.println("Exception in MessageReceived...");

            e.printStackTrace();

        }
    }

}       
2

First of all, for the client, bootstrap option should not start with 'child':

bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("keepAlive", true);

Also you don't use the same port on the client and the server!!

Second, you have no "close" strategy: when is your client suppose to know its job is done? How do you prevent the Thread from ending prematuraly? You should do this

SERVER HANDLER

public class ServerHandler extends SimpleChannelHandler{

    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e){
        byte[] resp=data.getBytes();//data is a String greater than 1024bytes;
        ChannelBuffer buffer=ChannelBuffers.buffer(resp.length);
        buffer.writerBytes(resp);
        e.getChannel().write(buffer);
        buffer.clear();
        e.getChannel.close();
    }
}

CLIENT BOOTSTRAP

public class Client{
    public static void main(String[] args){
        ChannelFactory channelFactory=new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());
        ClientBootstrap bootstrap=new ClientBootstrap(channelFactory);
        bootstrap.getPipeline().addLast("handler", new PhoneClientHandler());

        bootstrap.setOption("child.tcpNoDelay", true);
        bootstrap.setOption("child.keepAlive", true);

        // Start the connection attempt.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1",8181));

        // Wait until the connection is closed or the connection attempt fails.
        future.getChannel().getCloseFuture().awaitUninterruptibly();

        // Shut down thread pools to exit.
        bootstrap.releaseExternalResources();
    }
}

Finally, you need to understand better what you are doing by reading a lot of examples. They can be found inside org.jboss.netty.example package in the main bundled download.

0
1

I had the same Issue, try using Oio and not Nio! (simply change "nio" to "oio" and "Nio" to "Oio".

http://lists.jboss.org/pipermail/netty-users/2009-June/000891.html

1

RenaudBlue@ makes good points. In addition, I suggest switching to Netty4, which makes all ByteBufs dynamic, and which makes chunked reads/writes easier to manage. See "Porting the client".

For example,

private void sendNumbers() {
  // Do not send more than 4096 numbers.
  boolean finished = false;
  MessageBuf<Object> out = ctx.nextOutboundMessageBuffer();
  while (out.size() < 4096) {
      if (i <= count) {
          out.add(Integer.valueOf(i));
          i ++;
      } else {
          finished = true;
          break;
      }
  }

  ChannelFuture f = ctx.flush();
  if (!finished) {
      f.addListener(numberSender);
  }
}

private final ChannelFutureListener numberSender = new ChannelFutureListener() {
  @Override
  public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
          sendNumbers();
      }
  }
};

Netty4 also has type-safety for channel option configuration, which would have prevented the "child.tcpNoDelay" error.

But the big win for Netty4 is the well-defined thread model, which makes Netty much easier to use.

0

You need to setup FixedRecvByteBufAllocator of SocketChannel in childHandler() as follow:

bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(2 * 1024));
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, 5));
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(new StringDecoder());
                ...
            }
        });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.