From b15f974d92c34267e03c5db2d18b6d64bd085b80 Mon Sep 17 00:00:00 2001 From: Toby Doig Date: Tue, 27 Aug 2013 17:23:48 +0100 Subject: [PATCH] added optional timeout property to apply to the underlying socket --- lib/LazySocket.js | 25 +++++++++++++++++-------- test/integration/test-timeout.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 8 deletions(-) create mode 100644 test/integration/test-timeout.js diff --git a/lib/LazySocket.js b/lib/LazySocket.js index a3ed526..934f886 100644 --- a/lib/LazySocket.js +++ b/lib/LazySocket.js @@ -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; }; @@ -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() { diff --git a/test/integration/test-timeout.js b/test/integration/test-timeout.js new file mode 100644 index 0000000..0840b5b --- /dev/null +++ b/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); +}); +