Skip to content

Instantly share code, notes, and snippets.

@isaacs
Created February 8, 2013 00:32
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 isaacs/4735553 to your computer and use it in GitHub Desktop.
Save isaacs/4735553 to your computer and use it in GitHub Desktop.
// In this benchmark, we connect a client to the server, and write
// as many bytes as we can in the specified time (default = 10s)
var common = require('./common.js');
// if there are --dur=N and --len=N args, then
// run the function with those settings.
// if not, then queue up a bunch of child processes.
common.run(benchmark, {
dur: [1, 5],
len: [100, 102400, 1024 * 1024 * 16]
});
var TCP = process.binding('tcp_wrap').TCP;
var PORT = 1337;
var dur;
var len;
function benchmark(conf) {
dur = conf.dur;
len = conf.len;
server();
client();
}
function fail(syscall) {
var e = new Error(syscall + ' ' + errno);
e.errno = e.code = errno;
e.syscall = syscall;
throw e;
}
function server() {
var serverHandle = new TCP();
var r = serverHandle.bind('127.0.0.1', PORT);
if (r)
fail('bind');
var r = serverHandle.listen(511);
if (r)
fail('listen');
serverHandle.onconnection = function(clientHandle) {
if (!clientHandle)
fail('connect');
// the meat of the benchmark is right here:
common.start();
var bytes = 0;
setTimeout(function() {
common.end(bytes);
}, dur * 1000);
clientHandle.onread = function(buffer, offset, length) {
// we're not expecting to ever get an EOF from the client.
// just lots of data forever.
if (!buffer)
fail('read');
// don't slice the buffer. the point of this is to isolate, not
// simulate real traffic.
// var chunk = buffer.slice(offset, offset + length);
bytes += length;
};
clientHandle.readStart();
};
client();
}
function client() {
var buffer = new Buffer(len);
buffer.fill('x');
var clientHandle = new TCP();
var connectReq = clientHandle.connect('127.0.0.1', PORT);
if (!connectReq)
fail('connect');
clientHandle.readStart();
connectReq.oncomplete = function() {
while (clientHandle.writeQueueSize === 0)
write();
};
function write() {
var writeReq = clientHandle.writeBuffer(buffer);
if (!writeReq)
fail('write');
writeReq.oncomplete = afterWrite;
}
function afterWrite(status, handle, req) {
if (status)
fail('write');
while (clientHandle.writeQueueSize === 0)
write();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment