@Override
  public IMessage recognize(ByteBuffer buf) throws MessageParseException {
    // 长度尚不足,确保可读长度超过4字节
    if (buf.remaining() < IMessage.MIN_MESSAGE_LENGTH) {
      return null;
    }

    // 读取前4字节
    int len = buf.getShort(); // 预期长度
    short type = buf.getShort();
    if (type == MessageType.FLASH_POLICY) {
      // Policy请求
      boolean finished = false;
      // 找到结束的'\0'标志
      while (buf.remaining() > 0) {
        byte b = buf.get();
        if (b == 0) {
          finished = true;
          break;
        }
      }
      if (finished) {
        // Policy请求全部接收完毕
      } else {
        // 不足,下次继续
        return null;
      }
    } else {
      // 普通消息,检查长度是否满足
      if (buf.remaining() < len - IMessage.HEADER_SIZE) {
        return null;
      }
    }
    return createMessage(type);
  }
示例#2
0
 public static short readShort(ByteBuffer buffer) {
   if (buffer != null) {
     return buffer.getShort();
   } else {
     return 0;
   }
 }
示例#3
0
 protected static String readString(String charset, ByteBuffer buffer) {
   short len = buffer.getShort();
   byte[] bytes = new byte[len];
   buffer.get(bytes);
   try {
     return new String(bytes, charset);
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     return "";
   }
 }
示例#4
0
 /**
  * 从ByteBuffer解析得到PropertyBag
  *
  * @param buf 采用mina的ByteBuffer,因为这个支持自动增长
  * @return
  */
 public static PropertyBag readBuffer(ByteBuffer buf) {
   PropertyBag bag = new PropertyBag();
   short fieldCount = buf.getShort();
   for (int i = 0; i < fieldCount; i++) {
     int property = buf.getInt();
     ValueType type = getTypeCode(buf.get());
     Object val = ProtocolUtils.readValueFromPkt(buf, type);
     bag.put(property, val);
   }
   return bag;
 }