예제 #1
0
파일: Packet.java 프로젝트: eth4n/uni
  /**
   * Creates a byte array representation of this packets and returns the array
   *
   * @return
   */
  public byte[] serialize() {
    Logger.getInstance().println("Packet.serialize(" + this.toString() + ")", Logger.SPAM);
    // fetch data
    byte[] data = serializeData();
    byte[] seqNr = intToByteArray(sequenceNumber);

    // create new byte array with proceeding ID, then the senders adress and
    // the sequence number
    byte[] b = new byte[data.length + 1 + 2 + seqNr.length];
    // byte[] b = new byte[1472];

    // insert id
    b[0] = getId();
    // insert sender
    b[1] = sender;
    // insert receiver
    b[2] = receiver;
    // insert sequence number
    System.arraycopy(seqNr, 0, b, 3, seqNr.length);

    // copy data array to new byte array
    System.arraycopy(data, 0, b, HEADER_LENGTH, data.length);

    Logger.getInstance().println("Packet.serialize returns " + Logger.bytesToHex(b), Logger.SPAM);
    return b;
  }
예제 #2
0
파일: Packet.java 프로젝트: eth4n/uni
  /**
   * Reads an array of byte which should represent this packet.
   *
   * @param b
   */
  public void unserialize(byte[] b) {
    Logger.getInstance().println("Packet.unserialize(" + Logger.bytesToHex(b) + ")", Logger.SPAM);
    if (b.length < HEADER_LENGTH) {
      // TODO exception
    } else if (b[0] != getId()) {
      // TODO exception
    }

    // get sender
    byte[] tmp = new byte[4];
    sender = b[1];

    tmp = new byte[4];
    receiver = b[2];

    // get sequence number
    System.arraycopy(b, 3, tmp, 0, 4);
    sequenceNumber = byteArrayToInt(tmp);

    // unserialize data using offset to purge the packet's ID
    unserializeData(Arrays.copyOfRange(b, HEADER_LENGTH, b.length));
    Logger.getInstance().println("Packet.unserialize returns " + this.toString(), Logger.SPAM);
  }