Skip to content

Instantly share code, notes, and snippets.

@evanw
Created September 20, 2012 03:13
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save evanw/3753757 to your computer and use it in GitHub Desktop.
Save evanw/3753757 to your computer and use it in GitHub Desktop.
WebSocket Speed Test
{
"name": "ws-speed-test",
"version": "0.1.0",
"dependencies": {
"ws": "0.4.21"
}
}
var http = require('http');
var ws = require('ws');
var server = http.createServer(function(req, res) {
console.log(req.method + ' ' + req.url);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('\
<script>\
window.onload = function() {\
var ws = new WebSocket("ws://" + location.hostname + ":8001/");\
function log(text) {\
document.body.appendChild(document.createTextNode(text));\
document.body.appendChild(document.createElement("br"));\
}\
log("connecting to " + ws.URL);\
ws.onopen = function() {\
log("connected");\
};\
ws.onclose = function(e) {\
log("disconnected");\
};\
ws.onmessage = function(e) {\
var text = "got " + (e.data.length / (1024 * 1024)).toFixed(3) + " MB";\
ws.send(text);\
log(text);\
};\
};\
</script>\
');
});
console.log('listening on port 8000');
server.listen(8000);
var wss = new ws.Server({ port: 8001 });
wss.on('connection', function(ws) {
var onmessage = null;
ws.on('message', function(data) {
onmessage(data);
});
function test(sizeInMB, callback) {
var data = new Uint8Array(sizeInMB * 1024 * 1024);
for (var j = 0; j < data.length; j++) {
data[j] = 32 + Math.random() * 95;
}
var sendStart = Date.now();
var sendTime;
console.log('sending ' + sizeInMB.toFixed(3) + ' MB');
onmessage = function(data) {
var totalTime = (Date.now() - sendStart) / 1000;
console.log(data + ', took ' + totalTime.toFixed(3) + ' seconds');
times.push({ sizeInMB: sizeInMB, sendTime: sendTime, totalTime: totalTime });
setTimeout(callback, 500);
};
ws.send(data, function() {
sendTime = (Date.now() - sendStart) / 1000;
console.log('sent ' + sizeInMB.toFixed(3) + ' MB, took ' + sendTime.toFixed(3) + ' seconds');
});
}
var times = [];
var i = 0;
function next() {
i += 0.5;
if (i > 5) done();
else test(i, next);
}
function done() {
console.log('sizeInMB\tsendTime\ttotalTime');
for (var i = 0; i < times.length; i++) {
console.log(times[i].sizeInMB + '\t' + times[i].sendTime + '\t' + times[i].totalTime);
}
}
setTimeout(next, 500);
});
@PrestonL
Copy link

Would you release this under MIT or GPL license?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment