Skip to content

Commit 3d3c0d4

Browse files
committed
better 'listening' event handling
1 parent dce7205 commit 3d3c0d4

File tree

2 files changed

+13
-19
lines changed

2 files changed

+13
-19
lines changed

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
"inherits": "^2.0.1",
2626
"ip": "^0.3.0",
2727
"once": "^1.3.0",
28-
"run-parallel": "^1.0.0",
2928
"string2compact": "^1.1.1"
3029
},
3130
"devDependencies": {

server.js

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ var EventEmitter = require('events').EventEmitter
99
var http = require('http')
1010
var inherits = require('inherits')
1111
var ipLib = require('ip')
12-
var parallel = require('run-parallel')
1312
var string2compact = require('string2compact')
1413

1514
var NUM_ANNOUNCE_PEERS = 50
@@ -44,20 +43,29 @@ function Server (opts) {
4443

4544
self._trustProxy = !!opts.trustProxy
4645

46+
self.port = null
4747
self.torrents = {}
4848

4949
// default to starting an http server unless the user explictly says no
5050
if (opts.http !== false) {
5151
self._httpServer = http.createServer()
5252
self._httpServer.on('request', self._onHttpRequest.bind(self))
5353
self._httpServer.on('error', self._onError.bind(self))
54+
self._httpServer.on('listening', onListening)
5455
}
5556

5657
// default to starting a udp server unless the user explicitly says no
5758
if (opts.udp !== false) {
5859
self._udpServer = dgram.createSocket('udp4')
5960
self._udpServer.on('message', self._onUdpRequest.bind(self))
6061
self._udpServer.on('error', self._onError.bind(self))
62+
self._udpServer.on('listening', onListening)
63+
}
64+
65+
var num = !!self._httpServer + !!self._udpServer
66+
function onListening () {
67+
num -= 1
68+
if (num === 0) self.emit('listening', self.port)
6169
}
6270
}
6371

@@ -68,23 +76,10 @@ Server.prototype._onError = function (err) {
6876

6977
Server.prototype.listen = function (port, onlistening) {
7078
var self = this
71-
var tasks = []
72-
73-
if (onlistening) {
74-
self.once('listening', onlistening)
75-
}
76-
77-
self._httpServer && tasks.push(function (cb) {
78-
self._httpServer.listen(port.http || port, cb)
79-
})
80-
self._udpServer && tasks.push(function (cb) {
81-
self._udpServer.bind(port.udp || port, cb)
82-
})
83-
84-
parallel(tasks, function (err) {
85-
if (err) return self.emit('error', err)
86-
self.emit('listening', port)
87-
})
79+
self.port = port
80+
if (onlistening) self.once('listening', onlistening)
81+
self._httpServer && self._httpServer.listen(port.http || port)
82+
self._udpServer && self._udpServer.bind(port.udp || port)
8883
}
8984

9085
Server.prototype.close = function (cb) {

0 commit comments

Comments
 (0)