title: Netty Encoder And Decoder using Kryo Serialization
body: <p>I am new to Netty 4.0.29 and trying to make Custom Object Encoder and Object Decoder using Kryo as the serialization library and I am unable to make it work. As I am new to Netty maybe that is the reason I am messing up something. I am using <strong>MessageToMessageEncoder</strong> and <strong>MessageToMessageDecoder</strong></p>
  
  <p>Here is my encoder -</p>
  
  <pre><code>public class KryoEncoder extends  MessageToMessageEncoder&lt;Object&gt;{
  
      private Kryo kryo;
      private Output output;
  
      public KryoEncoder(Kryo kryo, int bufSize, int maxBufSize) {
          this.kryo = kryo;
          output = new Output(bufSize, maxBufSize);
      }
  
      @Override
      protected void encode(ChannelHandlerContext ctx, Object msg,
              List&lt;Object&gt; out) throws Exception {
          output.clear();
          kryo.writeClassAndObject(output, msg);
          int total = output.position();
          out.add(Unpooled.wrappedBuffer(output.getBuffer(), 0 , total));
      }
  
  }
  </code></pre>
  
  <p>Here is the decoder -</p>
  
  <pre><code>public class KryoDecoder extends MessageToMessageDecoder&lt;Object&gt;{
      private Kryo kryo;
      private Input input;
  
      public KryoDecoder (Kryo kryo) {
          this.kryo = kryo;
          input = new Input();
      }
  
      @Override
      protected void decode(ChannelHandlerContext ctx, Object msg, List&lt;Object&gt; out) throws Exception {
          ByteBuf buffer = (ByteBuf)msg;
          byte[] ar = new byte[buffer.readableBytes()];
          buffer.readBytes(ar);
          input.read(ar, buffer.readerIndex(), buffer.readableBytes());
          Object object = kryo.readClassAndObject(input);
          buffer.readerIndex(input.position());
          out.add(object);
      }
  }
  </code></pre>
  
  <p>Here is the short stack of exception which thrown and I know it is a null pointer exception and somewhere something is wrong in byte array in the decoder but not sure what.</p>
  
  <pre><code>Caused by: java.lang.NullPointerException
      at java.lang.System.arraycopy(Native Method)
      at com.esotericsoftware.kryo.io.Input.read(Input.java:254)
      at TestWithKryo.KryoDecoder.decode(KryoDecoder.java:31)
      at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:89)
      ... 14 more
  </code></pre>
  
  <p>The exception occurs when decoding and I have checked the encoder and checked the channelFuture when sending the encoded object and it did not throw any exception.</p>
  
  <p>Again as I am really new to netty I may have done something really wrong so please let me know.</p>