Skip to content

Instantly share code, notes, and snippets.

@aogriffiths
Created December 5, 2013 18:03
Show Gist options
  • Save aogriffiths/7810236 to your computer and use it in GitHub Desktop.
Save aogriffiths/7810236 to your computer and use it in GitHub Desktop.
With http pipelining this should take 100 - 200ms to run. actually takes over 10s.
// Code to test HTTP pipelining
var cluster = require('cluster')
var port = 50001; //port for server to listen on
var number_of_messages = 100; //number of client to server messages to send.
var delay = 100; //millisecons delay before server responds
function log(txt){
console.log( new Date().toISOString() + ' ' + txt);
}
if(cluster.isMaster){
//start the server
var express = require('express');
var app = express();
app.use("/resource", function(req,res){
var req_message = "";
req.on('data', function(chunk) {
req_message += chunk;
}); //drain the req
req.on('end', function() {
//add a pause here to fake some kind of latency
log(req_message + " - server got message.");
setTimeout(function(){
res.send("OK " + req_message);
log(req_message + " - server sent response.");
}, delay);
});
});
app.listen(port, function() {
log('Server with pid ' + process.pid + ' started. Listening on port ' + port + '.');
});
//fork a client
cluster.fork();
cluster.on("exit", function(client, code, signal){
log('Client with pid ' + client.process.pid + ' stopped. Server with pid ' + process.pid + ' stopping.' );
process.exit();
})
}else{
//start the client
log('Client with pid ' + process.pid + ' started. Will connect to server on port ' + port + '.');
var http = require('http');
var async = require('async');
var options = {hostname: 'localhost', port: port, method: 'POST', path: "/resource" };
http.globalAgent.maxSockets = 1;
function requester(req_message){
return function(callback){
var req = http.request(options, function(res){
var res_message = "";
res.on('data', function(chunk) {
res_message += chunk;
});
res.on('end', function() {
log(req_message + " - client got response (\"" + res_message +"\").");
callback(null, req_message + " - complete");
});
});
req.write(req_message);
req.end();
log(req_message + " - client sent message.");
}
}
var functions = [];
for (i=1;i<=number_of_messages;i++){
functions.push(requester("HTTP Message " + i));
}
var end = function(){
log('Client with pid ' + process.pid + ' stopping.' );
process.exit();
}
async.series(functions, end);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment