MonoTorrent开源项目学习 <SampleClient源码分析一>
下载MonoTorrent项目,使其编译成功。MonoTorrent项目下载地址https://nodeload.github.com/mono/monotorrent/zip/master
编译时需要手动导入nunit.framework.dll包到MonoTorrent.Tests项目中。nunit下载地址https://launchpadlibrarian.net/120714081/NUnit-2.6.2.zip
从项目的例子SampleClient入手,看看MonoTorrent中的类是如何组织和使用的:
1、class main中的静态成员:
1 static string dhtNodeFile; //记录dhtNodes文件的目录 2 static string basePath; //应用程序目录 3 static string downloadsPath; //下载文件所需路径 4 static string fastResumeFile; //fastresume文件路径,这个文件的用途还不知道 5 static torrentsPath; //种子文件的所在目录 6 static ClientEngine engin; //下载引擎 7 static List<TorrentManager> torrents; //torrentManagers,TorrentManager包括了针对一个Torrent的属性、操作、一些事件 8 static Top10Listener listener; //这个类继承自System.Diagnostics.TraceListener 为监视跟踪和调试输出的监听器
2、Main方法:初始化操作;程序退出或异常出现时,执行正确的清理操作;最后启动引擎方法。
1 static void Main(string[] args) 2 { 3 basePath = Environment.CurrentDirectory; 4 torrentsPath = Path.Combine(basePath,"Torrents"); 5 downloadsPath = Path.Combin(basePath,"Downloads"); 6 fastResumeFile = Path.Combin(basePath,"DhtNodes"); 7 torrents = new List<TorrentManager>(); 8 listener = new Top10Listener(10); 9 10 Console.CancelKeyPress += delegate{ shutdown(); }; 11 AppDomain.CurrentDomain.ProcessExit += delegate{ shutdown(); }; 12 AppDomain.CurrentDomain.UnhandleException += gelegate(object sender, UnhandleExeceptionEventArges e){ Console.WriteLine(e.ExceptionObject); shutdown(); }; 13 Thread.GetDomain().UnhandleException += delegate(object sender, UnhandleException e){ Console.WriteLine(e.ExceptionObject); shutdown(); }; 14 15 StartEngine(); 16 17 }
3、先看看shutdown()方法:
private static void shutdown() { BEncodingDictionary fastResume = new BEncodeDictionary(); //使用bt规范的bencode编码的字典对象 for(int i = 0; i < torrents.Count; i++) //遍历每个TorrentManager对象 { torrents[i].Stop(); //停止TorrentManager对象的服务 while(torrents[i].State!=TorrentState.Stopped) //等待到TorrentManager对象的状态为Stopped为止 { Console.Write("{0} is {1}",torrent[i].Torrent.Name,torrent[i].State); //TorrentManager中的Torrent对象是torrent对象的详细描述 Thread.Sleep(250); } fastResume.Add(torrents[i].Torrent.InfoHash.ToHex(),torrents[i].SaveFastResume().Encode()); //第一个参数:torrent种子对象的SHA-1的16进制编码,第二个参数:根据TorrentManager对象的InfoHash与BitField属性生成的FastResumed对象经过bencode编码后的BEncodingDictionary对象,其中TorrentManager.InfoHash==TorrentMenager.Torrent.InfoHash,是.torrent文件的唯一码 } #if !DISABLE_DHT File.WriteAllBytes(dhtNodeFile, engine.DhtEngine.SaveNodes()); //12 #endif File.WriteAllBytes(fastResumeFile, fastResume.encode()); //12 engein.Dispose(); // foreach(TranceListener lst in Debug.Listeners) // { lst.Flush(); lst.Close(); } Thraed.Sleep(2000); }

浙公网安备 33010602011771号