title: netty udp server with byteprocessor example
body: <p>I have been trying to learn netty in my spare time and have come to a bit of a road block which I was hoping to get some help on. I am trying to create a simple program whereby a datagram packet is sent in hex format which is then displayed in the server console.</p>
  
  <p>Server code</p>
  
  <pre><code>public final class UdpServer {
  
  private static final int PORT = Integer.parseInt(System.getProperty("port", "6565"));
  
  public static void main(String[] args) throws Exception {
      EventLoopGroup group = new NioEventLoopGroup();
      try {
          Bootstrap b = new Bootstrap();
          b.group(group)
                  .channel(NioDatagramChannel.class)
                  .handler(new UdpServerHandler());
  
          b.bind(PORT).sync().channel().closeFuture().await();
      } finally {
          group.shutdownGracefully();
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Udp Server Handler</p>
  
  <pre><code>public class UdpServerHandler extends SimpleChannelInboundHandler&lt;DatagramPacket&gt; {
  
  private ByteBuf buf;
  
  @Override
  public void handlerAdded(ChannelHandlerContext ctx) {
      buf = ctx.alloc().buffer(64);
  }
  
  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) {
      buf.release();
      buf = null;
  }
  
  @Override
  public void channelRead0 (ChannelHandlerContext ctx, DatagramPacket packet) {
      System.out.println("UDP messaged received");
      buf=packet.content();
      buf.forEachByte(new ByteProcessor() {
      @Override
          public boolean process(Byte value) {
          System.out.println(Integer.toHexString(value));
          return false;
      }
      });
  }
  
  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) {
      ctx.flush();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>So i watched Norman talk on youtube about netty best practices (<a href="https://www.youtube.com/watch?v=_GRIyCMNGGI" rel="nofollow">https://www.youtube.com/watch?v=_GRIyCMNGGI</a> at t=29:00) and tried to use the ByteProcessor method. Sadly, i couldnt find many example of this being used so I have struggled to get my code to work. I would like to point out I am a novice in java and still learning. </p>
  
  <p>I would like to display the hex output in the console using system.out.println, is my approach correct or have I tried this from the wrong angle? your help would be much appreciated</p>