private TryConnect ( TorrentManager manager ) : bool | ||
manager | TorrentManager | |
return | bool |
bool TryConnect(TorrentManager manager)
{
int i;
Peer peer;
if (!manager.Mode.CanAcceptConnections)
return false;
// If we have reached the max peers allowed for this torrent, don't connect to a new peer for this torrent
if (manager.Peers.ConnectedPeers.Count >= manager.Settings.MaxConnections)
return false;
// If the torrent isn't active, don't connect to a peer for it
if (!manager.Mode.CanAcceptConnections)
return false;
// If we are not seeding, we can connect to anyone. If we are seeding, we should only connect to a peer
// if they are not a seeder.
for (i = 0; i < manager.Peers.AvailablePeers.Count; i++)
if (manager.Mode.ShouldConnect (manager.Peers.AvailablePeers[i]))
break;
// If this is true, there were no peers in the available list to connect to.
if (i == manager.Peers.AvailablePeers.Count)
return false;
// Remove the peer from the lists so we can start connecting to him
peer = manager.Peers.AvailablePeers[i];
manager.Peers.AvailablePeers.RemoveAt(i);
// Do not try to connect to ourselves
if (peer.ConnectionUri.Port == manager.Engine.Listener.Endpoint.Port)
{
if (manager.Engine.Listener.Endpoint.Address.ToString() == peer.ConnectionUri.Host)
return false;
if (manager.Engine.Listener.Endpoint.Address == IPAddress.Any)
foreach (var intf in NetworkInterface.GetAllNetworkInterfaces())
if (intf.OperationalStatus == OperationalStatus.Up)
foreach (var ip in intf.GetIPProperties().UnicastAddresses)
if (ip.Address.ToString() == peer.ConnectionUri.Host)
return false;
}
if (ShouldBanPeer(peer))
return false;
// Connect to the peer
ConnectToPeer(manager, peer);
return true;
}
ConnectionManager::TryConnect ( ) : void |
public async Task SortByLeastConnections() { var engine = new ClientEngine(EngineSettingsBuilder.CreateForTests()); var manager = new ConnectionManager("test", engine.Settings, engine.Factories, engine.DiskManager); var torrents = new[] { await engine.AddAsync(new MagnetLink (new InfoHash(Enumerable.Repeat((byte)0, 20).ToArray())), "tmp"), await engine.AddAsync(new MagnetLink (new InfoHash(Enumerable.Repeat((byte)1, 20).ToArray())), "tmp"), await engine.AddAsync(new MagnetLink (new InfoHash(Enumerable.Repeat((byte)2, 20).ToArray())), "tmp") }; torrents[0].Peers.ConnectedPeers.Add(PeerId.CreateNull(1)); torrents[0].Peers.ConnectedPeers.Add(PeerId.CreateNull(1)); torrents[2].Peers.ConnectedPeers.Add(PeerId.CreateNull(1)); foreach (var torrent in torrents) { manager.Add(torrent); } manager.TryConnect(); Assert.AreEqual(torrents[1], manager.Torrents[0]); Assert.AreEqual(torrents[2], manager.Torrents[1]); Assert.AreEqual(torrents[0], manager.Torrents[2]); }