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

  • 相关阅读:
    PowerDesigner中利用数据库表反向生成PDM(jdk必须是32位)
    Struts2 Web Project 实现中文、英语的切换
    一张图解决Struts2添加源码
    Struts2配置文件struts.xml的编辑自动提示代码功能
    Hibernate多对一(注解)
    SQL Server 日期和时间函数
    ORACLE日期时间函数大全
    ORACLE中函数MONTHS_BETWEEN的使用
    SQL经典面试题及答案
    SQL数据库面试题以及答案
  • 原文地址:https://www.cnblogs.com/heroinss/p/10104391.html
Copyright © 2011-2022 走看看