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

  • 相关阅读:
    mycat
    人大金仓备份和还原
    文件断点上传,html5实现前端,java实现服务器
    MoChat
    PHP性能追踪及分析工具xhprof的安装与使用
    使用 satis 搭建一个私有的 Composer 包仓库
    sed命令用法详解
    rsync同步工具学习笔记
    服务器支持AspJpeg和JMail45_free.msi组件
    批处理——服务器的web文件备份
  • 原文地址:https://www.cnblogs.com/heroinss/p/10104391.html
Copyright © 2011-2022 走看看