netty字符串流分包

 @Override
  protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out)
      throws Exception {
    if (in.readableBytes() < 4) {
      LOG.error("MessageDecoder", "in.readableBytes < 4");
      return;
    }
    byte[] decoded = new byte[in.readableBytes()];
    in.markReaderIndex();
    int readLength = 0;
    byte head0 = in.readByte();
    if ('@' != (char) head0) {
      //            Log.e("MessageDecoder", "@");
      return;
    }
    decoded[0] = head0;
    readLength++;
    byte head1 = in.readByte();
    if ('#' != (char) head1) {
      //            Log.e("MessageDecoder", "#");
      return;
    }
    decoded[1] = head1;
    readLength++;
    byte head2 = in.readByte();
    if ('$' != (char) head2) {
      //            Log.e("MessageDecoder", "$");
      return;
    }
    decoded[2] = head2;
    readLength++;
    byte head3 = in.readByte();
    if ('%' != (char) head3) {
      //            Log.e("MessageDecoder", "%");
      return;
    }
    decoded[3] = head3;
    readLength++;
    if (in.readableBytes() >= 4) {
      in.readBytes(decoded, 4, 4); // ��ȡЭ�鳤��
    } else {
      in.resetReaderIndex();
      //            Log.e("MessageDecoder", "read length error..");
      return;
    }
    readLength += 4;
    byte[] btLength = Bytes2Hex.hexString2Bytes(new String(decoded, 4, 4));
    int cmdLength = ((btLength[0] & 0xFF) << 8) + (btLength[1] & 0xFF);
    if (in.readableBytes() >= (cmdLength - readLength)) {
      in.readBytes(decoded, 8, cmdLength - readLength);
      out.add(new String(decoded, 0, cmdLength, "UTF-8"));
    } else {
      LOG.error("MessageDecoder", "未读取到指定长度数据, cmdLength = " + cmdLength);
      in.resetReaderIndex();
    }
  }

字符串的读取和截断没有字节那么复杂,依靠readableBytes获取长度,自己控制怎么读取,怎么输出

posted @ 2018-12-11 19:11  heroinss  阅读(654)  评论(0编辑  收藏  举报