zoukankan      html  css  js  c++  java
  • 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获取长度,自己控制怎么读取,怎么输出

  • 相关阅读:
    Door man
    Borg Maze
    Agri-Net
    Highways
    Truck History
    Arctic Network
    QS Network
    用贝塞尔曲线实现水波效果
    在一个Label上设置多种颜色字体
    用UIImageView作出动画效果
  • 原文地址:https://www.cnblogs.com/heroinss/p/10104391.html
Copyright © 2011-2022 走看看