Skip to content

Instantly share code, notes, and snippets.

@chapko
Last active February 7, 2017 17:45
Show Gist options
  • Save chapko/237f191b6ce388ba91323a9125ba42c8 to your computer and use it in GitHub Desktop.
Save chapko/237f191b6ce388ba91323a9125ba42c8 to your computer and use it in GitHub Desktop.
var http = require('http');
var ForeverAgent = require('forever-agent');
var server = http.createServer(function (req, res) {
console.log('Server got request', req.url);
res.write(req.url);
// Get time to all async callbacks to be processed
setTimeout(function () {
res.end();
}, 50);
});
server.listen(3000);
var agent = new ForeverAgent({
maxSockets: 2
});
function runRequest(path, callback) {
var request = http.request({
method: 'GET',
hostname: '127.0.0.1',
port: 3000,
path: path,
agent: agent,
});
request.on('socket', function (socket) {
if (!socket.__requestId) {
socket.__requestId = path;
console.log('Request uses fresh new socket for %s', path);
} else {
console.log('Request uses old socket for %s from %s',
path, socket.__requestId);
}
});
request.on('response', function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
callback(null, data);
});
res.on('error', function (error) {
callback(error);
});
});
request.on('error', function (error) {
callback(error);
});
console.log('Client requests GET', path);
request.end();
return request;
}
function run() {
console.log('Start requests');
var queue = [
'/hello-1',
'/hello-2',
'/hello-3',
'/hello-4',
'/hello-5'
];
function exit(err) {
if (err) {
console.error('Error:', err);
}
console.log('Exit');
server.close();
}
function processQueue() {
var path = queue.shift();
if (path) {
var req = runRequest(path, function (error, data) {
if (error) {
console.error(error);
} else {
console.log('Client got response for GET %s: %s',
path, data);
}
processQueue();
});
// Unlucky /hello-2 has been randomly chosen to be destroyed
if (path === '/hello-2') {
req.on('response', function (res) {
console.log('Destroying socket for %s', path);
req.socket.destroy();
});
}
} else {
exit(null);
}
}
processQueue();
}
server.on('listening', run);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment