コード例 #1
0
 /**
  * Received when a peer request a piece. If the piece is available (which should always be the
  * case according to Bittorrent protocol) and we are able and willing to upload, the send the
  * piece to the peer
  *
  * @param peerID String
  * @param piece int
  * @param begin int
  * @param length int
  */
 public synchronized void peerRequest(String peerID, int piece, int begin, int length) {
   if (this.isPieceComplete(piece)) {
     DownloadTask dt = this.task.get(peerID);
     if (dt != null) {
       dt.ms.addMessageToQueue(
           new Message_PP(
               PeerProtocol.PIECE,
               Utils.concat(
                   Utils.intToByteArray(piece),
                   Utils.concat(
                       Utils.intToByteArray(begin), this.getPieceBlock(piece, begin, length)))));
       dt.peer.setULRate(length);
     }
     dt = null;
     this.pu.updateParameters(0, length, "");
   } else {
     try {
       this.task.get(peerID).end();
     } catch (Exception e) {
     }
     this.task.remove(peerID);
     this.peerList.remove(peerID);
     this.unchoken.remove(peerID);
   }
 }
コード例 #2
0
  /**
   * Save the downloaded files into the corresponding directories
   *
   * @deprecated
   */
  public synchronized void save() {
    synchronized (this) {
      synchronized (this.isComplete) {
        byte[] data = new byte[0];
        for (int i = 0; i < this.nbPieces; i++) {
          if (this.pieceList[i] == null) {

          } else {
            data = Utils.concat(data, this.pieceList[i].data());
          }
        }
        String saveAs = Constants.SAVEPATH;
        int offset = 0;
        if (this.nbOfFiles > 1) saveAs += this.torrent.saveAs + "/";
        for (int i = 0; i < this.nbOfFiles; i++) {
          try {
            new File(saveAs).mkdirs();
            FileOutputStream fos =
                new FileOutputStream(saveAs + ((String) (this.torrent.name.get(i))));
            fos.write(
                Utils.subArray(data, offset, ((Integer) (this.torrent.length.get(i))).intValue()));
            fos.flush();
            fos.close();
            offset += ((Integer) (this.torrent.length.get(i))).intValue();
          } catch (IOException ioe) {
            ioe.printStackTrace();
            System.err.println(
                "Error when saving the file " + ((String) (this.torrent.name.get(i))));
          }
        }
      }
    }
  }