Skip to content

Commit 387c1e5

Browse files
committed
udp client: clean up timer situation
1 parent cc4c73e commit 387c1e5

File tree

1 file changed

+14
-30
lines changed

1 file changed

+14
-30
lines changed

index.js

Lines changed: 14 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -170,15 +170,12 @@ Tracker.prototype._requestUdp = function (requestUrl, opts) {
170170
var socket = dgram.createSocket('udp4')
171171
var transactionId = new Buffer(hat(32), 'hex')
172172

173-
var timeout = setTimeout(function () {
174-
error('tracker request timed out')
175-
}, 15000)
176-
177-
if (opts.event !== EVENTS.stopped) {
173+
if (opts.event !== 'stopped') {
178174
// if we're sending a stopped message, we don't really care if it arrives, so don't
179175
// set a timer
180176
var timeout = setTimeout(function () {
181-
try { socket.close() } catch (err) {}
177+
timeout = null
178+
cleanup()
182179
error('tracker request timed out')
183180
}, 15000)
184181
}
@@ -217,6 +214,7 @@ Tracker.prototype._requestUdp = function (requestUrl, opts) {
217214
return
218215

219216
case 1: // announce
217+
cleanup()
220218
if (msg.length < 20) {
221219
return error('invalid announce message')
222220
}
@@ -237,46 +235,28 @@ Tracker.prototype._requestUdp = function (requestUrl, opts) {
237235
compact2string.multi(msg.slice(20)).forEach(function (addr) {
238236
self.client.emit('peer', addr)
239237
})
240-
241-
if (timeout) {
242-
clearTimeout(timeout)
243-
timeout = null
244-
}
245-
try { socket.close() } catch (err) {}
246-
return
238+
break
247239

248240
case 2: // scrape
241+
cleanup()
249242
if (msg.length < 20) {
250243
return error('invalid scrape message')
251244
}
252-
253245
self.client.emit('scrape', {
254246
announce: self._announceUrl,
255247
complete: msg.readUInt32BE(8),
256248
downloaded: msg.readUInt32BE(12),
257249
incomplete: msg.readUInt32BE(16)
258250
})
259-
260-
if (timeout) {
261-
clearTimeout(timeout)
262-
timeout = null
263-
}
264-
try { socket.close() } catch (err) {}
265-
return
251+
break
266252

267253
case 3: // error
254+
cleanup()
268255
if (msg.length < 8) {
269256
return error('invalid error message')
270257
}
271-
272258
self.client.emit('error', new Error(msg.slice(8).toString()))
273-
274-
if (timeout) {
275-
clearTimeout(timeout)
276-
timeout = null
277-
}
278-
try { socket.close() } catch (err) {}
279-
return
259+
break
280260
}
281261
})
282262

@@ -289,11 +269,15 @@ Tracker.prototype._requestUdp = function (requestUrl, opts) {
289269

290270
function error (message) {
291271
self.client.emit('error', new Error(message + ' (connecting to tracker ' + requestUrl + ')'))
272+
cleanup()
273+
}
274+
275+
function cleanup () {
292276
if (timeout) {
293277
clearTimeout(timeout)
294278
timeout = null
295279
}
296-
try { socket.close() } catch (err) { }
280+
try { socket.close() } catch (err) {}
297281
}
298282

299283
function genTransactionId () {

0 commit comments

Comments
 (0)