Skip to content

Instantly share code, notes, and snippets.

@nicokaiser
Created March 21, 2012 21:19
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 nicokaiser/2152933 to your computer and use it in GitHub Desktop.
Save nicokaiser/2152933 to your computer and use it in GitHub Desktop.
ws memory leak demo
/**
* The client opens 10,000 connections to the server and sends one 10k message.
* Every minutes, 2,000 new connections are openend and 2,000 random connections
* are closed (equally distributed interval).
*/
var util = require('util')
, WebSocket = require('ws');
// Config
var config = {
host: 'localhost'
, port: 10080
, concurrency: 10000
, connectionsPerMinute: 2000
};
// Stats
var stats = {
clientsTotal: 0
, clientsCurrent: 0
, messagesSent: 0
, messagesReceived: 0
, wsErrors: 0
};
// Connected clients
var clients = [];
// Display stats every second
setInterval(function() {
util.log(util.inspect(stats));
util.log(util.inspect(process.memoryUsage()));
}, 1000);
// Exit after 10 minutes
setTimeout(function() {
process.exit();
}, 10 * 60 * 1000);
// Initially open 20.000 connections
for (var i = 0; i < config.concurrency; i++) {
openWs();
}
// Open and close WS connections
setInterval(openWs, Math.ceil(60 * 1000 / config.connectionsPerMinute));
setInterval(closeWs, Math.ceil(60 * 1000 / config.connectionsPerMinute));
// Open a connection
function openWs() {
var ws = new WebSocket('ws://' + config.host + ':' + config.port + '/');
ws.on('error', function(e) {
stats.wsErrors++;
});
ws.on('open', function() {
clients.push(ws);
stats.clientsTotal++;
stats.clientsCurrent++;
ws.on('message', function(data) {
stats.messagesReceived++;
});
ws.on('close', function() {
stats.clientsCurrent--;
var index = clients.indexOf(ws);
if (index != -1) {
clients.splice(index, 1);
}
});
// Send 10k message
ws.send(new Array(2000).join("XXXXX"));
stats.messagesSent++;
});
}
// Close a random connection
function closeWs() {
if (clients.length > 0) {
var index = Math.floor(Math.random() * (clients.length - 1));
clients[index].close();
}
}
/**
* This ws server only accepts connections and sends "something" to the client.
* Every second, client count and memory usage is displayed as CSV.
*
* You might have to
* echo "* hard nofile 65536" >> /etc/security/limits.d/local.conf
* ulimit -n 30000
*/
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({port: 10080});
var clientsCount = 0;
console.log('clients,rss,heapTotal,heapUsed');
setInterval(function() {
console.log('%d,%d,%d,%d', clientsCount,
process.memoryUsage().rss,
process.memoryUsage().heapTotal,
process.memoryUsage().heapUsed);
}, 10000);
wss.on('connection', function(ws) {
clientsCount++;
ws.on('message', function(message) {});
ws.send('something');
ws.on('close', function() {
clientsCount--;
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment