MonoTorrent C#正在下载torrent



我正在创建一个torrent应用程序。我发现了一个名为";MonoTorrent";我决定用它。下面的代码有一些问题无法工作。我认为很多代码都被更改了,比如ITorrentManager不存在,也因为EngineSettings engineSettings = EngineSettings.DefaultSettings;DefaultSettings不存在。如果有人能帮我做这项工作,我尝试了很多mono-torrent的代码,但没有人能工作。

public void Main()
{
// An ITorrentManager is passed out of the engine when you load a torrent. This is
// used for controlling the torrent.
ITorrentManager torrentManager;
// These are the default settings for the engine for this session
EngineSettings engineSettings = EngineSettings.DefaultSettings;
// The default location to download files to on your HardDrive, like a downloads folder
// All files will be downloaded using this as the base directory. Single file torrents will
// go directly into this directory, multifile torrents will create a directory within this
// and download there.
engineSettings.DefaultSavePath = @"D:DownloadsTorrents";
// Maximum upload speed of 30 kB/sec. At upload speeds of less than 5kB/sec, there will
// be automatic download speed limiting to 5x the selected upload.
engineSettings.GlobalMaxUploadSpeed = 30;
// Every torrent loaded into the engine for this session will start off with these default settings
// unless other settings are specified.
TorrentSettings torrentSettings = TorrentSettings.DefaultSettings;
// Each torrent will be allowed a max of 10kB/sec upload speed
torrentSettings.MaxUploadSpeed = 10;
// Each torrent will have 4 upload slots to allow 2.5kB/sec per slot.
torrentSettings.UploadSlots = 4;
// Instantiate a new engine with the engineSettings and Default Torrent settings.
ClientEngine engine = new ClientEngine(engineSettings, torrentSettings);
// A torrent can be downloaded from the specified url, saved to the specified file and
// then loaded into the engine.
// torrentManager =engine.LoadTorrent(new Uri("http://example.com/example.torrent"), @"D:Downloadsexample.torrent");
// Alternatively a .torrent can just be loaded from the disk. This torrent will save
// to the DefaultSaveLocation as specified in the EngineSettings and will inherit the
// default settings that are set in the Engine.
//torrentManager = engine.LoadTorrent(@"D:DownloadsTorrentsMyTorrentFile.torrent");
// This torrent would use the supplied settings instead of using the ones that were
// supplied when instantiating the engine
torrentManager = engine.LoadTorrent(@"D:DownloadsTorrentsMyTorrentFile.torrent", TorrentSettings.DefaultSettings);
// If you have loaded multiple torrents into the engine, you can start them all at once with this:
// engine.Start();
// Or you can start one specific torrent by passing in that torrents ITorrentManager
engine.Start(torrentManager);
// You can hook into various events in order to display information on screen:
// Fired every time a peer is added through DHT, PEX or Tracker Updates
torrentManager.OnPeersAdded+=new EventHandler<PeersAddedEventArgs>(PeersAdded);
// Fired every time a piece is hashed
torrentManager.OnPieceHashed+=new EventHandler<PieceHashedEventArgs>(PieceHashed);
// Fired every time the torrent State changes (i.e. paused/hashing/downloading)
torrentManager.OnTorrentStateChanged+= new EventHandler<TorrentStateChangedEventArgs>(torrentStateChanged);
// Fired every time a piece changes. i.e. block sent/received/written to disk
torrentManager.PieceManager.OnPieceChanged+=new EventHandler<PieceEventArgs>(pieceStateChanged);
// Fired every time a connection is either created or destroyed
ClientEngine.connectionManager.OnPeerConnectionChanged+=new EventHandler<PeerConnectionEventArgs>(peerConnectionChanged);
// Fired every time a peer message is sent
ClientEngine.connectionManager.OnPeerMessages+= new EventHandler<PeerMessageEventArgs>(peerMessageSentOrRecieved);
// Keep running while the torrent isn't stopped or paused.
while (torrentManager.State != TorrentState.Stopped && torrentManager.State != TorrentState.Paused)
{
Console.WriteLine(torrentManager.Progress());
System.Threading.Thread.Sleep(1000);
if (torrentManager.Progress() == 100.0)
{
// If we want to stop a torrent, or the engine for whatever reason, we call engine.Stop()
// A tracker update *must* be performed before the engine is shut down, so you must
// wait for the waithandle to become signaled before continuing with the complete
// shutdown of your client. Otherwise stats will not get reported correctly.
WaitHandle[] handles = engine.Stop();
WaitHandle.WaitAll(handles);
return;
}
}
}
static void Main (string[] args)
{
CancellationTokenSource cancellation = new CancellationTokenSource ();
var task = MainAsync (args, cancellation.Token);
// We need to cleanup correctly when the user closes the window by using ctrl-c
// or an unhandled exception happens
Console.CancelKeyPress += delegate { cancellation.Cancel (); task.Wait (); };
AppDomain.CurrentDomain.ProcessExit += delegate { cancellation.Cancel (); task.Wait (); };
AppDomain.CurrentDomain.UnhandledException += delegate (object sender, UnhandledExceptionEventArgs e) { Console.WriteLine (e.ExceptionObject); cancellation.Cancel (); task.Wait (); };
Thread.GetDomain ().UnhandledException += delegate (object sender, UnhandledExceptionEventArgs e) { Console.WriteLine (e.ExceptionObject); cancellation.Cancel (); task.Wait (); };
task.Wait ();
}
static async Task MainAsync (string[] args, CancellationToken token)
{
// Give an example of how settings can be modified for the engine.
var settingBuilder = new EngineSettingsBuilder {
// Allow the engine to automatically forward ports using upnp/nat-pmp (if a compatible router is available)
AllowPortForwarding = true,
// Automatically save a cache of the DHT table when all torrents are stopped.
AutoSaveLoadDhtCache = true,
// Automatically save 'FastResume' data when TorrentManager.StopAsync is invoked, automatically load it
// before hash checking the torrent. Fast Resume data will be loaded as part of 'engine.AddAsync' if
// torrent metadata is available. Otherwise, if a magnetlink is used to download a torrent, fast resume
// data will be loaded after the metadata has been downloaded. 
AutoSaveLoadFastResume = true,
// If a MagnetLink is used to download a torrent, the engine will try to load a copy of the metadata
// it's cache directory. Otherwise the metadata will be downloaded and stored in the cache directory
// so it can be reloaded later.
AutoSaveLoadMagnetLinkMetadata = true,
// Use a fixed port to accept incoming connections from other peers.
ListenPort = 55123,
// Use a random port for DHT communications.
DhtPort = 55123,
};
using var engine = new ClientEngine (settingBuilder.ToSettings ());
Task task;
if (args.Length == 1 && args[0] == "--vlc") {
task = new VLCStream (engine).StreamAsync (InfoHash.FromHex ("AEE0F0082CC2F449412C1DD8AF4C58D9AAEE4B5C"), token);
} else if (args.Length == 1 && MagnetLink.TryParse (args[0], out MagnetLink link)) {
task = new MagnetLinkStreaming (engine).DownloadAsync (link, token);
} else {
task = new StandardDownloader (engine).DownloadAsync (token);
}
if (engine.Settings.AllowPortForwarding)
Console.WriteLine ("uPnP or NAT-PMP port mappings will be created for any ports needed by MonoTorrent");
try {
await task;
} catch (OperationCanceledException) {
}
foreach (var manager in engine.Torrents) {
var stoppingTask = manager.StopAsync ();
while (manager.State != TorrentState.Stopped) {
Console.WriteLine ("{0} is {1}", manager.Torrent.Name, manager.State);
await Task.WhenAll (stoppingTask, Task.Delay (250));
}
await stoppingTask;
if (engine.Settings.AutoSaveLoadFastResume)
Console.WriteLine ($"FastResume data for {manager.Torrent?.Name ?? manager.InfoHash.ToHex ()} has been written to disk.");
}
if (engine.Settings.AutoSaveLoadDhtCache)
Console.WriteLine ($"DHT cache has been written to disk.");
if (engine.Settings.AllowPortForwarding)
Console.WriteLine ("uPnP and NAT-PMP port mappings have been removed");
}

最新更新