Skip to content

Commit 6797a27

Browse files
committed
[bench] Add a benchmark for websockets throughput
1 parent 2bd9cd9 commit 6797a27

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

Diff for: benchmark/websockets-throughput.js

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
var crypto = require('crypto'),
2+
WebSocket = require('ws'),
3+
async = require('async'),
4+
httpProxy = require('../');
5+
6+
var SERVER_PORT = 8415,
7+
PROXY_PORT = 8514;
8+
9+
var testSets = [
10+
{
11+
size: 1024 * 1024, // 1 MB
12+
count: 128 // 128 MB
13+
},
14+
{
15+
size: 1024, // 1 KB,
16+
count: 1024 // 1 MB
17+
},
18+
{
19+
size: 128, // 128 B
20+
count: 1024 * 8 // 1 MB
21+
}
22+
];
23+
24+
testSets.forEach(function (set) {
25+
set.buffer = new Buffer(crypto.randomBytes(set.size));
26+
27+
set.buffers = [];
28+
for (var i = 0; i < set.count; i++) {
29+
set.buffers.push(set.buffer);
30+
}
31+
});
32+
33+
function runSet(set, callback) {
34+
function runAgainst(port, callback) {
35+
function send(sock) {
36+
sock.send(set.buffers[got++]);
37+
if (got === set.count) {
38+
t = new Date() - t;
39+
40+
server.close();
41+
proxy.close();
42+
43+
callback(null, t);
44+
}
45+
}
46+
47+
var server = new WebSocket.Server({ port: SERVER_PORT }),
48+
proxy = httpProxy.createServer(SERVER_PORT, 'localhost').listen(PROXY_PORT),
49+
client = new WebSocket('ws://localhost:' + port),
50+
got = 0,
51+
t = new Date();
52+
53+
server.on('connection', function (ws) {
54+
send(ws);
55+
56+
ws.on('message', function (msg) {
57+
send(ws);
58+
});
59+
});
60+
61+
client.on('message', function () {
62+
send(client);
63+
});
64+
}
65+
66+
async.series({
67+
server: async.apply(runAgainst, SERVER_PORT),
68+
proxy: async.apply(runAgainst, PROXY_PORT)
69+
}, function (err, results) {
70+
if (err) {
71+
throw err;
72+
}
73+
74+
var mb = (set.size * set.count) / (1024 * 1024);
75+
console.log(mb + ' MB');
76+
77+
Object.keys(results).forEach(function (key) {
78+
var t = results[key],
79+
throughput = mb / (t / 1000);
80+
81+
console.log(' ' + key + ' took ' + t + ' ms (' + throughput + ' MB/s)');
82+
});
83+
84+
callback();
85+
});
86+
}
87+
88+
async.forEachLimit(testSets, 1, runSet);

0 commit comments

Comments
 (0)