@@ -55,6 +55,8 @@ var cluster = null;
5555const errnoException = util . _errnoException ;
5656const exceptionWithHostPort = util . _exceptionWithHostPort ;
5757
58+ const { kTimeout, TIMEOUT_MAX , setUnrefTimeout } = require ( 'internal/timers' ) ;
59+
5860function noop ( ) { }
5961
6062function createHandle ( fd ) {
@@ -188,6 +190,7 @@ function Socket(options) {
188190 this . _handle = null ;
189191 this . _parent = null ;
190192 this . _host = null ;
193+ this [ kTimeout ] = null ;
191194
192195 if ( typeof options === 'number' )
193196 options = { fd : options } ; // Legacy interface.
@@ -259,9 +262,12 @@ function Socket(options) {
259262}
260263util . inherits ( Socket , stream . Duplex ) ;
261264
265+ // Refresh existing timeouts.
262266Socket . prototype . _unrefTimer = function _unrefTimer ( ) {
263- for ( var s = this ; s !== null ; s = s . _parent )
264- timers . _unrefActive ( s ) ;
267+ for ( var s = this ; s !== null ; s = s . _parent ) {
268+ if ( s [ kTimeout ] )
269+ timers . _unrefActive ( s [ kTimeout ] ) ;
270+ }
265271} ;
266272
267273// the user has called .end(), and all the bytes have been
@@ -380,14 +386,36 @@ Socket.prototype.listen = function() {
380386
381387
382388Socket . prototype . setTimeout = function ( msecs , callback ) {
389+ // Type checking identical to timers.enroll()
390+ if ( typeof msecs !== 'number' ) {
391+ throw new errors . TypeError ( 'ERR_INVALID_ARG_TYPE' , 'msecs' ,
392+ 'number' , msecs ) ;
393+ }
394+
395+ if ( msecs < 0 || ! isFinite ( msecs ) ) {
396+ throw new errors . RangeError ( 'ERR_VALUE_OUT_OF_RANGE' , 'msecs' ,
397+ 'a non-negative finite number' , msecs ) ;
398+ }
399+
400+ // Ensure that msecs fits into signed int32
401+ if ( msecs > TIMEOUT_MAX ) {
402+ process . emitWarning ( `${ msecs } does not fit into a 32-bit signed integer.` +
403+ `\nTimer duration was truncated to ${ TIMEOUT_MAX } .` ,
404+ 'TimeoutOverflowWarning' ) ;
405+ msecs = TIMEOUT_MAX ;
406+ }
407+
383408 if ( msecs === 0 ) {
384- timers . unenroll ( this ) ;
409+ clearTimeout ( this [ kTimeout ] ) ;
410+
385411 if ( callback ) {
386412 this . removeListener ( 'timeout' , callback ) ;
387413 }
388414 } else {
389- timers . enroll ( this , msecs ) ;
390- timers . _unrefActive ( this ) ;
415+ this [ kTimeout ] = setUnrefTimeout ( ( ) => {
416+ this . _onTimeout ( ) ;
417+ } , msecs ) ;
418+
391419 if ( callback ) {
392420 this . once ( 'timeout' , callback ) ;
393421 }
@@ -542,8 +570,9 @@ Socket.prototype._destroy = function(exception, cb) {
542570
543571 this . readable = this . writable = false ;
544572
545- for ( var s = this ; s !== null ; s = s . _parent )
546- timers . unenroll ( s ) ;
573+ for ( var s = this ; s !== null ; s = s . _parent ) {
574+ clearTimeout ( s [ kTimeout ] ) ;
575+ }
547576
548577 debug ( 'close' ) ;
549578 if ( this . _handle ) {
0 commit comments