diff --git a/lib/swarm.js b/lib/swarm.js index 5faa3c2..d12d053 100644 --- a/lib/swarm.js +++ b/lib/swarm.js @@ -1,6 +1,7 @@ module.exports = Swarm var debug = require('debug')('bittorrent-tracker') +var randomIterate = require('random-iterate') // Regard this as the default implementation of an interface that you // need to support when overriding Server.getSwarm() @@ -22,7 +23,7 @@ Swarm.prototype.announce = function (params, cb) { cb(null, { complete: self.complete, incomplete: self.incomplete, - peers: self._getPeers(params.numwant, params.peer_id) + peers: self._getPeers(params.numwant) }) } else { cb(new Error('invalid event')) @@ -92,16 +93,13 @@ Swarm.prototype._onAnnounce_update = function (params, peer) { } } -// TODO: randomize the peers that are given out -Swarm.prototype._getPeers = function (numWant, fromPeerId) { +Swarm.prototype._getPeers = function (numWant) { var peers = [] - for (var peerId in this.peers) { - if (peers.length >= numWant) break - if (peerId === fromPeerId) continue // skip self - + var ite = randomIterate(Object.keys(this.peers)) + while (true) { + var peerId = ite() + if (peers.length >= numWant || peerId == null) return peers var peer = this.peers[peerId] - if (!peer) continue // ignore null values - peers.push(peer) + if (peer) peers.push(peer) } - return peers } diff --git a/package.json b/package.json index cdf4ef7..77223f1 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "ip": "^0.3.0", "minimist": "^1.1.1", "once": "^1.3.0", + "random-iterate": "^1.0.1", "run-series": "^1.0.2", "simple-get": "^1.3.0", "simple-peer": "^5.0.0", diff --git a/test/server.js b/test/server.js index 8fdc8dd..c68048c 100644 --- a/test/server.js +++ b/test/server.js @@ -89,7 +89,7 @@ function serverTest (t, serverType, serverFamily) { }) client2.once('peer', function (addr) { - t.equal(addr, clientAddr + ':6881') + t.ok(addr === clientAddr + ':6881' || addr === clientAddr + ':6882') client2.stop() client2.once('update', function (data) {