mpetazzoni / ttorrent

BitTorrent Java library with tracker and download client
http://mpetazzoni.github.com/ttorrent/
Apache License 2.0
1.38k stars 502 forks source link

How to get download and upload speed in version 2.0? #241

Closed oc3anborn closed 5 years ago

oc3anborn commented 5 years ago

The question is in the header of the issue. I tried to get a solution from another issues and source code, but didn't find anything helpful.

Dead-off commented 5 years ago

currently, you can't get speed via some API method but you can calculate it manually. Just add a listener and override pieceDownloaded method where you can piece size from an argument

yoles commented 5 years ago

Can you show a quick exemple please ? It's a little bit hard for me to understand how it works

Dead-off commented 5 years ago

something like this should work. This example will print every second the average download speed until download will not be finished.

SimpleClient client = new SimpleClient();
    TorrentManager torrentManager = client.downloadTorrentAsync("torrent.file", "download/dir", InetAddress.getLocalHost());
    long start = System.currentTimeMillis();
    final AtomicLong downloadedBytes = new AtomicLong();
    final Semaphore semaphore = new Semaphore(0);
    torrentManager.addListener(new TorrentListenerWrapper() {
      @Override
      public void pieceDownloaded(PieceInformation pieceInformation, PeerInformation peerInformation) {
        downloadedBytes.addAndGet(pieceInformation.getSize());
      }

      @Override
      public void downloadComplete() {
        semaphore.release();
      }
    });

    while (!semaphore.tryAcquire(1, TimeUnit.SECONDS)) {
      System.out.println("average download speed " + (downloadedBytes.get() / (System.currentTimeMillis() - start)) + " bytes/ms");
    }
yoles commented 5 years ago

Thank you so much !