title: Netty - Correct usage of a decoder
body: <p>I have once again a question about Netty. </p>
  
  <p>My scenario is:</p>
  
  <p>incoming message (TCP) = header[byte,int,byte] body[bytes]</p>
  
  <p>I have a packet class which holds the header &amp; body with some methods.
  My channel pipeline is:</p>
  
  <blockquote>
    <p>ProtocolDecoder > SessionHandler</p>
  </blockquote>
  
  <p>My idea of the ProtocolDecoder is that it receives a message, splits it up and creates a Packet variable to pass on to the next handler in the pipeline.</p>
  
  <p>The code of the ProtocolDecoder class:</p>
  
  <pre><code>public class ProtocolDecoder extends ByteToMessageDecoder {
  
      @Override
      protected void decode(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out) throws Exception {
  
      int opCode;
      int length;
      boolean encrypt;
  
      if (in.readableBytes() &lt; 6) {
          return;
      }
  
      if (out.size() != 1) {
          Packet pa = new Packet();
          opCode = in.readByte();
          length = in.readInt();
          encrypt = in.readByte() == 1;
          pa.setOpcode(opCode);
          pa.setEncrypted(encrypt);
          pa.setLength(length);
          out.add(pa);
          in.discardReadBytes();
      }
  
      Packet p = (Packet) out.get(0);
  
      if (in.readableBytes() &gt;= p.getLength()) {
          p.setPayload(in.copy());
      }
      }
  
  }
  </code></pre>
  
  <p>The SessionHandler has this code:</p>
  
  <pre><code>@Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  Packet p = (Packet) msg;
  System.out.println("Packet: " + p.toString());
  }
  </code></pre>
  
  <p>So my two questions are:</p>
  
  <ul>
  <li>Is this the correct usage of the ByteToMessageDecoder?</li>
  <li>How do I solve the error: "java.lang.UnsupportedOperationException: direct buffer" when I access the direct buffer (<code>array()</code> method) in the <code>toString()</code> method of the packet?</li>
  </ul>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I remade the decoder like supposed to and this is my outcome: <a href="http://pastebin.com/wQz2LbYT" rel="nofollow">http://pastebin.com/wQz2LbYT</a></p>
  
  <p>I wasn't sure if I had to put the code here because this post would become pretty big. Anyways it seems to work fine now :) thanks alot!</p>