File tree 2 files changed +47
-8
lines changed 2 files changed +47
-8
lines changed Original file line number Diff line number Diff line change @@ -6,13 +6,14 @@ function LazySocket(properties) {
6
6
7
7
this . port = properties . port ;
8
8
this . host = properties . host ;
9
+ this . timeout = properties . timeout || 0 ;
9
10
10
11
this . _socket = null ;
11
12
this . _callbacks = [ ] ;
12
13
}
13
14
14
- LazySocket . createConnection = function ( port , host ) {
15
- var socket = new this ( { port : port , host : host } ) ;
15
+ LazySocket . createConnection = function ( port , host , timeout ) {
16
+ var socket = new this ( { port : port , host : host , timeout : timeout } ) ;
16
17
return socket ;
17
18
} ;
18
19
@@ -56,15 +57,23 @@ LazySocket.prototype._lazyConnect = function() {
56
57
if ( this . _socket ) return ;
57
58
58
59
var self = this ;
59
-
60
+ var onerror = function ( err ) {
61
+ self . _socket = null ;
62
+ self . _callbacks . forEach ( function ( cb ) {
63
+ cb ( err ) ;
64
+ } ) ;
65
+ } ;
66
+
60
67
this . _socket = net
61
68
. createConnection ( this . port , this . host )
62
- . once ( 'error' , function ( err ) {
63
- self . _socket = null ;
64
- self . _callbacks . forEach ( function ( cb ) {
65
- cb ( err ) ;
66
- } ) ;
69
+ . once ( 'error' , onerror ) ;
70
+
71
+ if ( this . timeout ) {
72
+ this . _socket . setTimeout ( this . timeout , function ( ) {
73
+ self . _socket . end ( ) ;
74
+ onerror ( 'timeout' ) ;
67
75
} ) ;
76
+ }
68
77
} ;
69
78
70
79
LazySocket . prototype . end = function ( ) {
Original file line number Diff line number Diff line change
1
+ var common = require ( '../common' ) ;
2
+ var assert = require ( 'assert' ) ;
3
+ var net = require ( 'net' ) ;
4
+ var LazySocket = common . LazySocket ;
5
+ var wasClosed = false ;
6
+
7
+ var server = net . createServer ( function ( socket ) {
8
+ // when a connection is received, close it after 1 second as a
9
+ // cleanup step. our test should have done its thing by then.
10
+ setTimeout ( function ( ) {
11
+ socket . end ( ) ;
12
+ server . close ( ) ;
13
+ } , 1000 ) ;
14
+ socket . once ( 'end' , function ( ) {
15
+ wasClosed = true ;
16
+ } ) ;
17
+ } ) ;
18
+
19
+ server . listen ( common . port , function ( ) {
20
+ var socket = LazySocket . createConnection ( common . port , undefined /* host */ , 250 /* timeout */ ) ;
21
+ socket . _lazyConnect ( ) ;
22
+ // socket is now open and should timeout after 250ms of idleness.
23
+ assert . ok ( ! wasClosed ) ;
24
+ setTimeout ( function ( ) {
25
+ // socket should have timed out after 250ms which was about 250ms ago.
26
+ assert . ok ( wasClosed ) ;
27
+ socket . destroy ( ) ;
28
+ } , 500 ) ;
29
+ } ) ;
30
+
You can’t perform that action at this time.
0 commit comments