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获取长度,自己控制怎么读取,怎么输出

  • 相关阅读:
    Scala中隐式转换(implicit conversion)的优先顺序
    protege4.0使用中的理论
    国外程序员整理的 C++ 资源大全
    什么是本体论?
    深入分析C++引用
    在基于对话框的MFC程序中,使程序在任务栏中不显示图标
    PhoneGap搭建运行环境(3.2版本)
    [JS代码]如何判断ipad或者iphone是否为横屏或者竖屏
    windwos iis 7.5 使用html 报405错误
    NodeJs 开源
  • 原文地址:https://www.cnblogs.com/heroinss/p/10104391.html
Copyright © 2011-2022 走看看