Enable DHT
Version 1 (Alan McGovern, 04/20/2009 10:57 PM)
| 1 | 1 | h1. Enable DHT |
|
|---|---|---|---|
| 2 | 1 | ||
| 3 | 1 | ||
| 4 | 1 | ||
| 5 | 1 | <pre><code class="java"> |
|
| 6 | 1 | ||
| 7 | 1 | public void StartDht (ClientEngine engine, int port) |
|
| 8 | 1 | { |
|
| 9 | 1 | // Send/receive DHT messages on the specified port |
|
| 10 | 1 | IPEndPoint listenAddress = new IPEndPoint (IPAddress.Any, port); |
|
| 11 | 1 | ||
| 12 | 1 | // Create a listener which will process incoming/outgoing dht messages |
|
| 13 | 1 | DhtListener listener = new UdpListener (listenAddress); |
|
| 14 | 1 | ||
| 15 | 1 | // Create the dht engine |
|
| 16 | 1 | DhtEngine dht = new DhtEngine (listener); |
|
| 17 | 1 | ||
| 18 | 1 | // Connect the Dht engine to the MonoTorrent engine |
|
| 19 | 1 | engine.RegisterDht (dht); |
|
| 20 | 1 | ||
| 21 | 1 | // Start listening for dht messages and activate the DHT engine |
|
| 22 | 1 | listener.Start (); |
|
| 23 | 1 | ||
| 24 | 1 | // If there are existing DHT nodes stored on disk, load them |
|
| 25 | 1 | // into the DHT engine so we can try and avoid a (very slow) |
|
| 26 | 1 | // full bootstrap |
|
| 27 | 1 | byte[] nodes = null; |
|
| 28 | 1 | if (File.Exists (path)) |
|
| 29 | 1 | nodes = File.ReadAllBytes (nodes); |
|
| 30 | 1 | dht.Start (nodes); |
|
| 31 | 1 | } |
|
| 32 | 1 | ||
| 33 | 1 | public void StopDht (DhtEngine dht, DhtListener listener) |
|
| 34 | 1 | { |
|
| 35 | 1 | // Stop the listener and dht engine. This does not |
|
| 36 | 1 | // clear internal data so the DHT can be started again |
|
| 37 | 1 | // later without needing a full bootstrap. |
|
| 38 | 1 | listener.Stop (); |
|
| 39 | 1 | dht.Stop (); |
|
| 40 | 1 | ||
| 41 | 1 | // Save all known dht nodes to disk so they can be restored |
|
| 42 | 1 | // later. This is *highly* recommended as it makes startup |
|
| 43 | 1 | // much much faster. |
|
| 44 | 1 | File.WriteAllBytes (path, dht.SaveNodes ()); |
|
| 45 | 1 | } |
|
| 46 | 1 | </code> |
|
| 47 | 1 | </pre> |