Skip to content

Commit

Permalink
Merge pull request #2 from tobyattagman/add-timeout-property
Browse files Browse the repository at this point in the history
Add timeout property
  • Loading branch information
tobyattagman committed Aug 27, 2013
2 parents 75680f6 + b15f974 commit 4eef023
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 8 deletions.
25 changes: 17 additions & 8 deletions lib/LazySocket.js
Expand Up @@ -6,13 +6,14 @@ function LazySocket(properties) {

this.port = properties.port;
this.host = properties.host;
this.timeout = properties.timeout || 0;

this._socket = null;
this._callbacks = [];
}

LazySocket.createConnection = function(port, host) {
var socket = new this({port: port, host: host});
LazySocket.createConnection = function(port, host, timeout) {
var socket = new this({port: port, host: host, timeout: timeout});
return socket;
};

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

var self = this;

var onerror = function(err) {
self._socket = null;
self._callbacks.forEach(function(cb) {
cb(err);
});
};

this._socket = net
.createConnection(this.port, this.host)
.once('error', function(err) {
self._socket = null;
self._callbacks.forEach(function(cb) {
cb(err);
});
.once('error', onerror);

if (this.timeout) {
this._socket.setTimeout(this.timeout, function() {
self._socket.end();
onerror('timeout');
});
}
};

LazySocket.prototype.end = function() {
Expand Down
30 changes: 30 additions & 0 deletions test/integration/test-timeout.js
@@ -0,0 +1,30 @@
var common = require('../common');
var assert = require('assert');
var net = require('net');
var LazySocket = common.LazySocket;
var wasClosed = false;

var server = net.createServer(function(socket) {
// when a connection is received, close it after 1 second as a
// cleanup step. our test should have done its thing by then.
setTimeout(function() {
socket.end();
server.close();
}, 1000);
socket.once('end', function() {
wasClosed = true;
});
});

server.listen(common.port, function() {
var socket = LazySocket.createConnection(common.port, undefined /* host */, 250 /* timeout */);
socket._lazyConnect();
// socket is now open and should timeout after 250ms of idleness.
assert.ok(!wasClosed);
setTimeout(function() {
// socket should have timed out after 250ms which was about 250ms ago.
assert.ok(wasClosed);
socket.destroy();
}, 500);
});

0 comments on commit 4eef023

Please sign in to comment.