Giter Site home page Giter Site logo

alanmcgovern / monotorrent Goto Github PK

View Code? Open in Web Editor NEW
1.1K 78.0 392.0 11.17 MB

The official repository for MonoTorrent, a bittorrent library for .NET

Home Page: https://github.com/alanmcgovern/monotorrent

License: MIT License

C# 99.99% Makefile 0.01% Batchfile 0.01%
bittorrent torrent csharp c-sharp dotnet dotnet-standard torrent-download torrent-downloader torrent-tracker

monotorrent's Introduction

MonoTorrent

Nuget Nuget (with prereleases) Nuget

Build status (master) Test Status (master) code coverage (master)

Azure DevOps builds (branch) Azure DevOps tests Azure DevOps coverage (branch)

Azure DevOps builds (branch) Azure DevOps tests Azure DevOps coverage (branch)

Backers on Open Collective

Supported Specifications

This is a list of all the BEPs which have been implemented in MonoTorrent. A full list of all available BEPs can be seen here

Final/Active BEPs

Accepted BEPs

Draft BEPs

Others

Supported Client Features

The client downloads torrents and has a wide range of functionality.

  • Prioritise specific files.

  • Selective file downloading (including the ability to not download specific files).

  • Rarest first piece picking (takes priorisation into account).

  • End-game mode to boost the last 1-2% of the download.

  • Sequential downloading (for media files).

  • Per-torrent download/upload rate limiting.

  • Overall download/upload rate limiting.

  • In memory cache to reduce disk reads.

  • Auto-throttling if the download rate exceeds the piece verification/disk write rate.

  • IPV4 connections.

  • IPV6 connections.

  • IP address ban lists.

  • Creating torrents from a single file, a folder, or arbitrary files in arbitrary folders.

  • Fast resume data can be saved/restored to avoid hashing the data every time a torrent is started.

  • Incremental piece hashing (reduces disk reads by incrementally hashing each block in a piece as it is received).

  • Partial Hash Checking. If a TorrentFile has its Priority set to DoNotDownload then these files will be skipped when the hash check runs. If the priority is raised then the files will be automatically hash checked (if needed) before any piece is downloaded.

  • Sparse files (NTFS filesystem).

  • UPnP port forwarding.

  • NAT-PMP port forwarding.

  • Creating and using Magnet URI.

Supported Tracker Features

This is a standard bittorrent tracker server.

  • HTTP announce and scrape requests.
  • UDP announce and scrape requests.
  • Compact peer responses (reduces bandwidth)
  • Optionally allows unregistered torrents. In this mode the tracker will begin maintaining peer lists for a torrent as soon as the first announce request is received.

JetBrains

A special thank you to JetBrains for supplying a free license to their tooling so I can continue to deliver great features on this opensource project.

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

monotorrent's People

Contributors

aaronsace avatar alanmcgovern avatar almcgo-stripe avatar an3orik avatar bigbluehat avatar borigas avatar cjac avatar ddevault avatar dufoli avatar dwarfmeat avatar ilyalatt avatar issueg2k4g34j2g avatar jpmikkers avatar justscribe avatar kellyelton avatar migueldeicaza avatar monkeywithacupcake avatar mr-const avatar onefingercodingwarrior avatar peters avatar phil-scott-78 avatar rcawston avatar samhocevar avatar sicgames avatar skelder avatar somecoolword avatar vlasenkoalexey avatar winterqt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

monotorrent's Issues

peer remoteUrl port diffirent my expect

I make app using mono-torrent, thanks

I have trouble what I create app using port 21111

envoriment : 2 computer each launch app pcA(21111) <--> pcB(21112)

when I debugging using pcA
pcA(debugging: 21111) <---- pcB(211112)

I expect coming connecting remote port is 21112

pcA(debugging: 21111) <---- pcB(51569...52019... )

but 51569...52019... some ramdom port comming

where is send peer change port code
but i can't found

recently,
I add upnp code but can't
NAT <-> non-Nat
NAT <-> NAT

I think find code where is change port
then fix NAT problem

How to download only one file from large torrent

Hello!

How to download only one file from large torrent?

I tried this code:

string allowed = "test.exe";

Torrent torrent = Torrent.Load(TorrentFile.FullName);

for (int i = 0; i < torrent.Files.Length; i++)
{
if (!torrent.Files[i].Path.Contains(allowed))
{
torrent.Files[i].Priority = Priority.DoNotDownload;
}
else
{
torrent.Files[i].Priority = Priority.Highest;
}
}

But with this code monotorrent whatever downloads all files.

How to fix that?

Thanks

Data Validation needed on Peers received from tracker

A peer without a port from the tracker results in the following exception. This can and does routinely happen. Especially on open source torrents (IE: Ubuntu)

System.ArgumentOutOfRangeException was unhandled by user code
HResult=-2146233086
Message=Specified argument was out of the range of valid values.
Parameter name: port
Source=System
ParamName=port
StackTrace:
at System.Net.IPEndPoint..ctor(IPAddress address, Int32 port)
at MonoTorrent.Client.Connections.IPV4Connection..ctor(Uri uri) in c:\Users\xxx\Documents\GitHub\xxx\MonoTorrent\MonoTorrent.Client\PeerConnections\TCPConnection.cs:line 83
InnerException:

Can't get MonoTorrent to download

I'm trying to download some files and both with the SampleClient, and using the code below, it always stays at Downloading, and 0 percent.
I've tried downloading various torrents including Linux distros.

What could cause this?

Console.WriteLine("Torrent test...");
Torrent t = Torrent.Load("/path/to/torrent");
TorrentSettings s = new TorrentSettings();
s.MaxConnections = 100;
s.InitialSeedingEnabled = true;
s.MaxDownloadSpeed = 500;
s.MaxUploadSpeed = 100;
s.UploadSlots = 4;
s.EnablePeerExchange = true;
s.UseDht = true;
TorrentManager tm = new TorrentManager(t, "/path/to/save/location", s);
EngineSettings es = new EngineSettings();
es.AllowedEncryption = EncryptionTypes.All;
es.ListenPort = 22239; // forwarded, both UDP and TCP
es.PreferEncryption = true;

ClientEngine engine = new ClientEngine(es);
engine.Register(tm);
tm.Start();
Console.WriteLine(engine.IsRunning); // outputs True
while (true)
{
    Console.WriteLine(tm.State.ToString() + ", " + tm.Progress); // just keeps outputting "Downloading, 0"
    System.Threading.Thread.Sleep(1000);
}

is ChangePicker function correct?

https://github.com/mono/monotorrent/blob/774a12494006acd21c117d36a9303732ac509139/src/MonoTorrent/MonoTorrent.Client/Managers/PieceManager.cs

line 218,219

    internal void ChangePicker(PiecePicker picker, BitField bitfield, TorrentFile[] files)
    {
        if (unhashedPieces.Length != bitfield.Length)
            unhashedPieces = new BitField(bitfield.Length);


        picker = new IgnoringPicker(bitfield, picker); <----
        picker = new IgnoringPicker(unhashedPieces, picker); <----
     
        IEnumerable<Piece> pieces = Picker == null ? new List<Piece>() : Picker.ExportActiveRequests();
        picker.Initialise(bitfield, files, pieces);
        this.picker = picker;
    }

`

picker is always picker = new IgnoringPicker(unhashedPieces, picker);?

bug in dht

mscorlib : System.IndexOutOfRangeException
Индекс находился вне границ массива.
в System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) в System.Collections.Generic.Dictionary2.Add(TKey key, TValue value)
в MonoTorrent.Dht.Messages.MessageFactory.RegisterSend(QueryMessage message) в ....\MonoTorrent.Dht\MessageFactory.cs:строка 72
в MonoTorrent.Dht.MessageLoop.EnqueueSend(Message message, IPEndPoint endpoint) в ...\MonoTorrent.Dht\MessageLoop.cs:строка 243
в MonoTorrent.Dht.MessageLoop.EnqueueSend(Message message, Node node) в ...\MonoTorrent.Dht\MessageLoop.cs:строка 248
в MonoTorrent.Dht.Tasks.SendQueryTask.Execute() в ...\MonoTorrent.Dht\Tasks\SendMessageTask.cs:строка 55
в MonoTorrent.Dht.Tasks.GetPeersTask.SendGetPeers(Node n) в ...\MonoTorrent.Dht\Tasks\GetPeersTask.cs:строка 60
в MonoTorrent.Dht.Tasks.GetPeersTask.b__0() в ...\MonoTorrent.Dht\Tasks\GetPeersTask.cs:строка 46
в MonoTorrent.Client.MainLoop.DelegateTask.Execute() в ...\MonoTorrent\MonoTorrent.Client\MainLoop.cs:строка 132
в MonoTorrent.Client.MainLoop.Loop() в ...\MonoTorrent\MonoTorrent.Client\MainLoop.cs:строка 161

Sending messages to the tracker

Monoterrent does not send messages to the tracker about status changes:

stopped: Must be sent to the tracker if the client is shutting down gracefully.
completed: Must be sent to the tracker when the download completes. However, must not be sent if the download was already 100% complete when the client started. Presumably, this is to allow the tracker to increment the "completed downloads" metric based solely on this event.

maybe, there are some others, but this is most important for me.
(http://wiki.theory.org/BitTorrentSpecification)

Wrong Time Stamp

Hi
There is a wrong with time stamp. When I use the monoTorrent to create a new torrent, the created time add 8 hour in time zone UTC+8. The code in TorrentCreator.cs

            TimeSpan span = DateTime.Now - new DateTime (1970, 1, 1);
            torrent ["creation date"] = new BEncodedNumber ((long) span.TotalSeconds);

need to change to

            TimeSpan span = DateTime.UtcNow - new DateTime (1970, 1, 1);
            torrent ["creation date"] = new BEncodedNumber ((long) span.TotalSeconds);

Cant stop TorrentManager

Hello!

I have a problem, when i use TorrentManager.Stop() torrent manager hangs for always.

Thanks!

tracker did not respond to the connect request but utorrent can connect to the trackers

Good day,

i setup a single peer (using utorrent) torrent file on the following trackers

udp://tracker.openbittorrent.com:80/announce
udp://tracker.publicbt.com:80/announce
udp://tracker.ccc.de:80/announce

the torrent file is located at
https://dl.dropbox.com/u/4317204/DADDY%20WHY%20DID%20YOU%20EAT%20MY%20FRIES.mp3.torrent

utorrent can download this, but i can't seem to download this using ttorrent's sample download code

failure message says: tracker did not respond to the connect request

ChokeUnchokeManager mod from changeset bdd3a7f7 seems incorrect

I have been trying to wrap my head around how the ChokeUnchokeManager works, and noticed something seems incorrect to me. Changeset bdd3a7f7 has this comment:

"If the speed limits are zero, then we should not skip the review"

The code looks like this:

bool skipDownload = (isDownloading && ( /*some math involving download rates */);
skipDownload = skipDownload && owningTorrent.Settings.MaxDownloadSpeed > 0;

...

else if (minimumTimeBetweenReviews > 0 && (SecondsBetween(timeOfLastReview, DateTime.Now) >= minimumTimeBetweenReviews)
&& (skipDownload || skipUpload))
//Based on the time of the last review, a new review is due
//There are more interested peers than available upload slots
//If we're downloading, the download rate is insufficient to skip the review
//If we're seeding, the upload rate is insufficient to skip the review
//So, we need a review
ExecuteReview();

It seems like the logic is inverted. If the limits are zero, then the review is always skipped. Indeed, I put a breakpoint in ExecuteReview, and it never seems to get called except on the initial call, and when the download completes and the torrent transitions to seeding mode.

0 size files

Sometimes monotorernts creates 0 size files in Download directory. If redownload this torrent again, files will be downloaded properly.

Local Peer Discovery not working with multiple network interfaces

Bug:
Local Peer Discovery only works on the default network interface, the multicast packet is not send to other interfaces. (e.g. you have a wlan&lan adapter only one will it work). Especially a problem with virtual nics.

Fix:
Iterate all nics capable of multicast and send a multicast packet for each one.
This change worked for me (not really 'clean', mostly based on https://stackoverflow.com/a/14603966 ):
https://github.com/Dwarfmeat/monotorrent/blob/master/src/MonoTorrent/MonoTorrent.Client/Managers/LocalPeerManager.cs

you should compare peers by host and port

you should compare peers without peerId by host and port
possible scenarios:

  1. two or more torrent clients on one computer (for example: test environment)
  2. two or more clients in local network (external to our client) with NAT and port mapping or UPnP
  3. torrent client changed port, we got endpoints with old port and new port. If we add enpoint with old port first, then we don't add endpoint with new port and couldn't connect to peer

Stuck downloading on last pieces

I have problem if most of all seed send bad pieces. It's not important why. For example, i have 10 bad seeds and 2 good(weebseeds). On last 1-3 pieces i can't finish downloading because alwayse got hash failed.
In PieceManager in function PieceDataReceived i changed this:
if (peers [i].Peer.TotalHashFails == 5)
peers[i].ConnectionManager.CleanupSocket (id, "Too many hash fails");
to
if (peers[i].Peer.TotalHashFails >= 5)
peers[i].ConnectionManager.CleanupSocket(peers[i], "Too many hash fails");
Now i don't have peers with more than 8 hash fail(8 is still possible). So after few minutes I have only WebSeeds. Yeah I changed DownloadLogic in Mode.cs to have WebSeed always. But I still have problem.
Webseeds can stuck and I don't get any response from them.

It will be good if monotorrent switch to webseed more quickly and finish downloading. Can anybody help me?

TorrentManager should not call UpdateChunks on the engine's rate limiter

We have had ongoing problems with global rate limits not slowing torrents down. To reproduce

1- start a torrent download with these settings
EngineSettings.MaxDownloadSpeed = 10*1024
TorrentSettings.MaxDownloadSpeed = 0; //unlimited.

Observe the torrent download speed on a high throughput network. We see it skyrocket and stay consistently above 10k

We traced this down to the fact that the TorrentManger calls UpdateChunks on the engine's rate limiter by way of a rate limiter group. However, it passes the torrent managers max rate of 0, and the torrent's observed down rate. It does this in addition to calling UpdateChunks on its own rate limiter.

The call from the torrent manager overwrites the chunk calculation that the engine last did, and sets the unlimited field in the limiter to true. That in turn kills the global limiter's ability to throttle the speed. We decided that the torrrent manager shouldn't be calling the global limiter's UpdateChunks, and fixed it by adding some ugly flags that tell the torrent manager to skip it. It does still call TryProcess on it though.

I will try to get this pushed to our forked monotorrent repo. I would invite you do pursue a cleaner implementation than what we did though.

Main directory is not visible in Torrent.Files

Hi.
If you have a .torrent with some files in a directory, something like that :

  • Directory1
    • File1
    • File2
    • Directory2
      • File3
    • Directory3
      • File4

Torrent.Files will look like this :
File1
File2
Directory2/File3
Directory3/File4

On torrenteditor, i can't see it too, but i have a meta-data called "Directory".
Can you do something about it ?

There is an problem whit BigInteger class

In MonoTorrent.Dht project,the NodeId class has a method below:

 internal BEncodedString BencodedString()
{
       return new BEncodedString(value.GetBytes());
}

The method convert BigInteger num to bytes, the BigInteger .GetBytes return a dynamic length bytes,
sometime the length less than 20. but in dht , it shoud be a 20 length value
original BigInteger .GetBytes:

 public byte[] GetBytes()
        {
            if (this == 0) return new byte[1];

            int numBits = BitCount();
            int numBytes = numBits >> 3;
            if ((numBits & 0x7) != 0)
                numBytes++;

            byte[] result = new byte[numBytes]; //here is a dynamic length

I modify the BigInteger .GetBytes mothed like this:

 public byte[] GetBytes()
        {
            if (this == 0) return new byte[1];

            int numBits = BitCount();
            int numBytes = numBits >> 3;
            if ((numBits & 0x7) != 0)
                numBytes++;

            byte[] result = new byte[20];

Finding the new Docs

Hi guys, I've been struggling finding any other Torrent lib for my project, and this one is the best option available.

I'm wondering where's the newest documentation of the site, this one is quite old, since the difference is almost 8 years-ish been left.

Thanks!

Can not download files from the Magnet Link.How?EX?

This project is great. Undeniable.
Create torrent file and download the file from torrent file.It work.great.
I have only two problems
The A,Official prompted example input port.
Can I get a torrent file, how do I know what port to connect to it? It makes me not understand. This port is the server or local computer it?I use “6969”.
However, this value should not be fixed. And should not allow the user to enter, but to judge by the program, I think.
The B[I don't know whether it is BUG, but I still haven't found the solution yet.]
I download files from a Magnet Link, start without downloading occurs, there is no error, the program did not crash.I do not know where I was wrong, there is no such official examples.
This is my code:
MagnetLink mag = new MagnetLink("magnet:?xt=urn:btih:BC8A29FE40F6D771A0441E09679F264FD85375A2"); TorrentManager manager = new TorrentManager(mag, downloadsPath, torrentDefaults, downloadsPath);engine.Register(manager);manager.Start();
The state has been the "Metadata",Not Downing.Who can write an example of it?Thank you.
Thanks again Developers.

Why i couldn't download any .torrent file?

when i try to download .torrent file with sampleClient, it always tell me "Tracker did not respond to the connect requests" or "the tracker could not be contracted",but the same file could be downloaded with qbittorrent.anyone knows what happend?

StoppingMode and waiting Tracker Announce

if (manager.TrackerManager.CurrentTracker != null)
handle.AddHandle(manager.TrackerManager.Announce(TorrentEvent.Stopped), "Announcing");

it holds sometimes forever, is it really necessary and what if i disable it?

There are 8 failing tests

There are 8 failing tests, i noticed some of them required elevated privileges so i ran them again as administrator.

Here's the report:

<MonoTorrent.Tests> (331 tests), 8 tests failed
  MonoTorrent.Tests.Client (185 tests), 8 tests failed
    TestWebSeed (7 tests), 6 tests failed: One or more child tests had errors
      ChunkedRequest, Success
      MultipleChunkedRequests, Failed: System.NullReferenceException : Object reference not set to an instance of an object.
      RecieveFirst, Failed: System.NullReferenceException : Object reference not set to an instance of an object.
      SendFirst, Failed: System.NullReferenceException : Object reference not set to an instance of an object.
      SingleFileTorrent, Failed: System.Net.WebException : Unable to connect to the remote server ----> System.Net.Sockets.SocketException : No connect
      TestInactiveServer, Failed: An unexpected exception type was thrown Expected: System.Net.WebException but was: System.InvalidOperationException : C
      TestPartialData, Failed: An unexpected exception type was thrown Expected: System.Net.WebException but was: System.InvalidOperationException : C
    UdpTrackerTests (12 tests), 2 tests failed: One or more child tests had errors
      AnnounceTest, Failed:  Expected: True But was: False
      ScrapeTest, Failed:  #3 Expected: True But was: False

Gist available here: https://gist.github.com/peters/4975677

Client download speed

I'm experiencing some issues regarding the download speed when using the Monotorrent client engine.
I have set up a monotorrent based tracker, two clients and a torrent, with the following results:

  1. Monotorrent client -> uTorrent client: download speed ~80 KB/s
  2. uTorrent client -> uTorrent client: download speed ~500 KB/s

Same tracker, computers, torrent file, internet connections. Only difference is using Monotorrent client at one end.

I'm really stuck here. Any help would be appreciated.

ArgumentOutOfRangeException in TCPConnection.cs

I've tried following the sample. When the engine started and the torrent starts downloading, few seconds later an System.ArgumentOutOfRangeException exception is thrown at:

MonoTorrent\MonoTorrent.Client\PeerConnections\TCPConnection.cs::Line84

//edit: uri.Port argument is -1

Does someone know if this is my fault and how I can fix this on my end? Or is this a bug in monotorrent?

Monotorrent may crush during change current date to some month back

Subj can be produced for after client torrent engine start if change current time for some month back. This is so becouse of bug in MonoTorrent\MonoTorrent.Common\TimeoutDispatcher.cs line 155:

if (interval < TimeSpan.Zero)
{
interval = TimeSpan.Zero;
}
must be:

if (interval < TimeSpan.Zero || interval.TotalMilliseconds > Int32.MaxValue)
{
interval = TimeSpan.Zero;
}

Please fix it :)

Download Piece

Hello, how do I download a separate piece ?

Torrent torrent = Torrent.Load("file.torrent");
byte[] array = DownloadPiece(torrent.Files[0].StartPieceIndex));

byte[] DownloadPiece(int index)
{
   // 
}

Peer download rates are incorrect resulting in slow/capped peer download speeds.

There is a bug in the SpeedMonitor Tick() that results in all connected peers have a calculated download speed of 0kb/s.

This is caused by Tick() only updating if over 800ms have elapsed since last called, but the logic that calls Tick() for each peer runs every 500ms meaning the time since lastUpdated is never greater than 800ms.

This is the root cause of the poor download speeds, as the download speed are used to work out how many active requests to have for a given peer, since mono thinks it's downloading from all peers at 0kb/s it only sends one request at a time, resulting in single 16kb requests per a peer.

Thus limiting the speed of each connection to 1.64 Mbit/sec for a RRT of 80ms.
Making it basically impossible to get decent speeds unless seeding from many peers.

After fixing the logic in Tick() mono correctly scales up the active request rates per a peer as intended removing the download speed handicap.

cannot download a torrent url, but uTorrent can download this?

I cannot download this torrent file and mono torrent is not working.but utorrent can download it. what is wrong here?

 EngineSettings settings = new EngineSettings();
            settings.AllowedEncryption = EncryptionTypes.All;
            settings.SavePath = Path.Combine("I:\\TestTorrent\\Test", "torrents");
            if (!Directory.Exists(settings.SavePath))
                Directory.CreateDirectory(settings.SavePath);
           var  engine = new ClientEngine(settings);
            engine.CriticalException += Engine_CriticalException;
            engine.ChangeListenEndpoint(new IPEndPoint(IPAddress.Any, 6969));

            var torrent = Torrent.Load(new Uri("http://filesbee.com/9VsQMI"), "I:\\TestTorrent\\Test.torrent");

            TorrentManager manager = new TorrentManager(torrent, engine.Settings.SavePath, new TorrentSettings());
            manager.TorrentStateChanged += Manager_TorrentStateChanged;
            engine.Register(manager);

            manager.Start();
            Console.Write("Started...");
            Console.ReadLine();

engine stuck

Hi:

ConnectionManager.cs

1、if you delete one torrent mission, then the engine stuck
2、engine will stuck forever if one torrent file has no available peers even other torrent manager with many available peers

internal void TryConnect()
{
int lastConnect = TryConnectIndex < engine.Torrents.Count ? TryConnectIndex : 0;//1
bool connected = true;
Int32 nRound = 0;

        // If we have already reached our max connections globally, don't try to connect to a new peer
        while (OpenConnections < this.MaxOpenConnections && PendingConnects.Count < this.MaxHalfOpenConnections && connected)
        {
            nRound = 0;
            connected = false;
            // Check each torrent manager in turn to see if they have any peers we want to connect to
            for (int i = lastConnect; i < engine.Torrents.Count; ++i)
            {
                if (TryConnect(engine.Torrents[i]))
                {
                    connected = true;
                    TryConnectIndex = (i + 1) % engine.Torrents.Count;
                }
                else//only if all the torrents connection failed, we can break the loop//2
                {
                    ++nRound;
                    connected = nRound != engine.Torrents.Count;
                }
            }

            lastConnect = 0;
        }
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.