title: How to parse and validate a WebSocket frame in Java?
body: <p>I wrote a WebSocket frame decoder in Java:</p>
  
  <pre><code>private byte[] decodeFrame(byte[] _rawIn) {
          int maskIndex = 2;
          byte[] maskBytes = new byte[4];
  
          if ((_rawIn[1] &amp; (byte) 127) == 126) {
              maskIndex = 4;
          } else if ((_rawIn[1] &amp; (byte) 127) == 127) {
              maskIndex = 10;
          }
  
          System.arraycopy(_rawIn, maskIndex, maskBytes, 0, 4);
  
          byte[] message = new byte[_rawIn.length - maskIndex - 4];
  
          for (int i = maskIndex + 4; i &lt; _rawIn.length; i++) {
              message[i - maskIndex - 4] = (byte) (_rawIn[i] ^ maskBytes[(i - maskIndex - 4) % 4]);
          }
  
          return message;
      }
  </code></pre>
  
  <p>It works, but I have no idea how to validate a frame in order to make sure that it decodes only valid frames. </p>
  
  <p>The protocol description <code>http://tools.ietf.org/html/rfc6455</code> unfortunately does not tell much about frame-validation.</p>