Skip to content

Instantly share code, notes, and snippets.

@DanBUK
Created January 11, 2011 22:55
Show Gist options
  • Save DanBUK/775336 to your computer and use it in GitHub Desktop.
Save DanBUK/775336 to your computer and use it in GitHub Desktop.
This hack enables node.js to handle connection timeouts.
var net = require('net');
var sys = require('sys');
// START setConnTimeout hack
net.Stream.prototype._orig_connect = net.Stream.prototype.connect;
net.Stream.prototype.connect = function () {
var self = this;
if (typeof self.conn_timeout !== 'undefined' && self.conn_timeout > 0) {
self.addListener('connect', function () {
clearTimeout(self.conn_timer);
});
self.conn_timer = setTimeout(function () {
self.emit('timeout');
self.destroy();
}, self.conn_timeout);
}
self._orig_connect.apply(self, arguments);
};
net.Stream.prototype.setConnTimeout = function (timeout) {
this.conn_timeout = parseInt(timeout);
};
// END setConnTimeout hack
var sock = new net.Stream();
sock.setConnTimeout(1000);
sock.addListener('error', function (err) {
sys.puts("Error: " + sys.inspect(err));
});
sock.addListener('conn_timeout', function () {
sys.puts("Connection timeout occured.");
});
sock.connect(12345, "23.23.23.23");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment