listen() without port picks random port

This commit is contained in:
Feross Aboukhadijeh 2014-08-16 19:05:56 -07:00
parent 9b2a8ea6a2
commit 01286e2ee7
3 changed files with 27 additions and 11 deletions

View File

@ -25,12 +25,12 @@
"inherits": "^2.0.1",
"ip": "^0.3.0",
"once": "^1.3.0",
"portfinder": "^0.2.1",
"string2compact": "^1.1.1"
},
"devDependencies": {
"magnet-uri": "^2.0.1",
"parse-torrent": "^1.1.0",
"portfinder": "^0.2.1",
"tape": "^2.13.3"
},
"homepage": "http://webtorrent.io",

View File

@ -9,8 +9,12 @@ var EventEmitter = require('events').EventEmitter
var http = require('http')
var inherits = require('inherits')
var ipLib = require('ip')
var portfinder = require('portfinder')
var string2compact = require('string2compact')
// Use random port above 1024
portfinder.basePort = Math.floor(Math.random() * 60000) + 1025
var NUM_ANNOUNCE_PEERS = 50
var MAX_ANNOUNCE_PEERS = 82
var REMOVE_IPV6_RE = /^::ffff:/
@ -43,6 +47,7 @@ function Server (opts) {
self._trustProxy = !!opts.trustProxy
self.listening = false
self.port = null
self.torrents = {}
@ -65,7 +70,10 @@ function Server (opts) {
var num = !!self._httpServer + !!self._udpServer
function onListening () {
num -= 1
if (num === 0) self.emit('listening', self.port)
if (num === 0) {
self.listening = true
self.emit('listening', self.port)
}
}
}
@ -76,10 +84,22 @@ Server.prototype._onError = function (err) {
Server.prototype.listen = function (port, onlistening) {
var self = this
self.port = port
if (typeof port === 'function') {
onlistening = port
port = undefined
}
if (self.listening) throw new Error('server already listening')
if (onlistening) self.once('listening', onlistening)
self._httpServer && self._httpServer.listen(port.http || port)
self._udpServer && self._udpServer.bind(port.udp || port)
function onPort (err, port) {
if (err) return self.emit('error', err)
self.port = port
self._httpServer && self._httpServer.listen(port.http || port)
self._udpServer && self._udpServer.bind(port.udp || port)
}
if (port) onPort(null, port)
else portfinder.getPort(onPort)
}
Server.prototype.close = function (cb) {

View File

@ -1,5 +1,4 @@
var Client = require('../')
var portfinder = require('portfinder')
var Server = require('../').Server
var test = require('tape')
@ -9,7 +8,7 @@ var peerId2 = '12345678901234567890'
var torrentLength = 50000
function serverTest (t, serverType) {
t.plan(27)
t.plan(26)
var opts = serverType === 'http' ? { udp: false } : { http: false }
var server = new Server(opts)
@ -26,10 +25,7 @@ function serverTest (t, serverType) {
t.pass('server listening')
})
portfinder.getPort(function (err, port) {
t.error(err, 'found free port')
server.listen(port)
server.listen(function (port) {
var announceUrl = 'http://127.0.0.1:' + port + '/announce'
var client = new Client(peerId, 6881, {