Skip to content

Instantly share code, notes, and snippets.

@byrney
Created December 14, 2021 09:38
Show Gist options
  • Save byrney/f4df10bd85292368f4b7a91bc3705c8b to your computer and use it in GitHub Desktop.
Save byrney/f4df10bd85292368f4b7a91bc3705c8b to your computer and use it in GitHub Desktop.
Testing performance of socket.write in node
const net = require('net');
const stream = require('stream');
function createSource(count, batchSize, sep){
const s = stream.Readable();
let buf = '';
for(let i = 0; i < count; i++){
if(i > 0 && (i % batchSize) == 0) {
s.push(buf + sep);
buf = '';
}
buf = buf + '.';
}
buf.length > 0 && s.push(buf);
s.push(null);
return s;
}
function send(host, port, opt) {
const source = createSource(opt.count, opt.batchSize, opt.sep);
const client = new net.Socket();
client.connect({
host: host,
port: port
}, function () {
console.log('Connected:', host, port, 'Sending ', opt.count, ' in batches of ', opt.batchSize);
console.time('sending');
stream.pipeline(source, client, () => {
console.timeEnd('sending')
client.destroy();
})
});
}
// run:
// while true ; do nc -l 127.0.0.1 9999 | wc -wc ; done
// in another window to act as the server
// count: number of characters to send in total (not counting sep)
// batchSize: how many characters to push onto stream at a time
// sep: character to push to separate the batches
send('127.0.0.1', 9999, {count: 1e6, batchSize: 100000, sep: ''})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment