Skip to content

Commit 4eef023

Browse files
author
tobyattagman
committed
Merge pull request #2 from tobyattagman/add-timeout-property
Add timeout property
2 parents 75680f6 + b15f974 commit 4eef023

File tree

2 files changed

+47
-8
lines changed

2 files changed

+47
-8
lines changed

lib/LazySocket.js

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ function LazySocket(properties) {
66

77
this.port = properties.port;
88
this.host = properties.host;
9+
this.timeout = properties.timeout || 0;
910

1011
this._socket = null;
1112
this._callbacks = [];
1213
}
1314

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});
1617
return socket;
1718
};
1819

@@ -56,15 +57,23 @@ LazySocket.prototype._lazyConnect = function() {
5657
if (this._socket) return;
5758

5859
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+
6067
this._socket = net
6168
.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');
6775
});
76+
}
6877
};
6978

7079
LazySocket.prototype.end = function() {

test/integration/test-timeout.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+

0 commit comments

Comments
 (0)