Skip to content

Instantly share code, notes, and snippets.

@jeffdev11
Forked from midnightcodr/README.md
Last active August 15, 2023 21:30
Show Gist options
  • Save jeffdev11/fa89ce09784781ddfd447547c66127cc to your computer and use it in GitHub Desktop.
Save jeffdev11/fa89ce09784781ddfd447547c66127cc to your computer and use it in GitHub Desktop.
websocket performance test using ws
npm install yargs ws
node server.js
node client.js
const WebSocket = require('ws');
const argv = require('yargs').argv;
const clients = argv.clients || 6000;
const interval = argv.interval || 50; // em milissegundos
let connectedClients = 0;
const now = () => {
return new Date().getTime();
};
async function createClients() {
for (let i = 0; i < clients; i++) {
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', () => {
connectedClients++;
console.log(`client ${connectedClients} connected`);
// Envie uma mensagem inicial ao servidor com a hora atual
ws.send(JSON.stringify({ start: now() }));
});
ws.on('error', (error) => {
console.error('WebSocket Error:', error);
});
ws.on('message', (data) => {
const msg = JSON.parse(data);
if(msg.start) {
msg.roundtrip = now() - msg.start; // roundtrip time in ms
console.log('received from server: ', JSON.stringify(msg));
} else {
console.log('received from server: ', data.toString());
}
});
if (i % 10 === 9) {
await new Promise(resolve => setTimeout(resolve, interval));
}
}
}
createClients(); // Chamando a função assíncrona
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 8080
});
const now = () => {
return new Date().getTime();
}
// Uma variável para armazenar a contagem de conexões ativas
let activeConnections = 0;
wss.on('connection', (ws) => {
activeConnections++; // Incrementa a contagem quando uma nova conexão é estabelecida
ws.on('message', function(data) {
var msg = JSON.parse(data);
msg.took = now() - msg.start; // time in ms from client to server
ws.send(JSON.stringify(msg));
});
// Reduz a contagem quando a conexão é fechada
ws.on('close', () => {
activeConnections--;
});
});
// Exibe o número de conexões ativas a cada segundo
setInterval(() => {
console.log(`Conexões ativas: ${activeConnections}`);
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment