示例#1
0
  public void write(@NotNull ByteBuffer buf) {
    if (buf == null) {
      throw new IllegalArgumentException("buf must be not null");
    }

    header.write(buf);
    for (Command command : commands) {
      command.write(buf);
    }
  }
示例#2
0
  public static Packet read(@NotNull ByteBuffer buf) throws ParseException {
    if (buf == null) {
      throw new IllegalArgumentException("buf must be not null");
    }

    try {
      PacketHeader header = PacketHeader.read(buf);

      if (buf.remaining() != header.size - PacketHeader.HEADER_LENGTH) {
        throw new ParseException(
            "Packet header size = %d, but buf remaining = %d", header.size, buf.remaining());
      }

      if (header.isHello()) {
        buf.mark();
        int connectionFlag = buf.get() & 0xFF;
        buf.position(buf.position() + 2); // skip 2 bytes
        int connectionUptime = buf.get() & 0xFF;
        buf.reset();
        String payload = Utils.readHexString(buf);
        return new PacketHello(header, connectionFlag, connectionUptime, payload);
      }

      ArrayList<Command> commands = new ArrayList<>();
      while (buf.hasRemaining()) {
        commands.add(Command.read(buf));
      }
      return new Packet(header, commands);

    } catch (ParseException ex) {
      throw ex;
    } catch (Throwable ex) {
      buf.rewind();
      throw new ParseException(
          "Can't parse packet %s cause ", Utils.readHexString(buf), ex.getMessage());
    }
  }