Skip to content

Instantly share code, notes, and snippets.

@robrich
Created May 1, 2014 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robrich/74bff4b51358a3470160 to your computer and use it in GitHub Desktop.
Save robrich/74bff4b51358a3470160 to your computer and use it in GitHub Desktop.
Experiments on request timeouts when a server isn't listening in different platforms
/*jshint node:true */
'use strict';
/*
What happens if there's no server listening when we do the request?
- win32: socket.on('timeout' fires and req.abort() fires req.on('error', e) with e.code === 'ECONNRESET'
- else: req.on('error', e) fires imediately with e.code === 'ECONNREFUSED'
*/
var http = require('http');
var prettyHrtime = require('pretty-hrtime');
var start = process.hrtime();
var socketTimeout = 50;
var callbackTimeout = 1500;
// FRAGILE: ASSUME: Nothing is listening on http://localhost:9000/
var req = http.request({
host: 'localhost',
port: 9000,
path: '/',
method: 'GET'
});
req.on('socket', function (s) {
s.setTimeout(socketTimeout);
s.on('timeout', function () {
console.log('socket timeout');
console.log(prettyHrtime(process.hrtime(start)));
console.log();
req.abort();
unsetTimeout();
});
});
req.on('error', function (e) {
console.log('error');
console.log(prettyHrtime(process.hrtime(start)));
console.log(e);
console.log();
unsetTimeout();
});
req.on('response', function (res) {
console.log('response');
console.log(prettyHrtime(process.hrtime(start)));
console.log(res);
console.log();
unsetTimeout();
});
var handle = setTimeout(function () {
console.log('timeout');
console.log(prettyHrtime(process.hrtime(start)));
console.log();
req.abort();
}, callbackTimeout);
function unsetTimeout() {
if (handle) {
clearTimeout(handle);
handle = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment