Skip to content

Instantly share code, notes, and snippets.

@EdNutting
Created May 21, 2023 14:51
Show Gist options
  • Save EdNutting/a69b5514497fa306480a1e71c49d5956 to your computer and use it in GitHub Desktop.
Save EdNutting/a69b5514497fa306480a1e71c49d5956 to your computer and use it in GitHub Desktop.
NodeJS Websocket Test Client
let WebSocketClient = require('websocket').client;
let uuid = require('uuid');
function runClient(clientIndex) {
const port = process.argv[2] || 9160;
const id = `${uuid.v4()}-${port}-${clientIndex.toString().padStart(3, '-')}`;
let timeoutId = null;
const client = new WebSocketClient();
client.on('connectFailed', function (error) {
console.info(`[${clientIndex}] Connect failed: ` + error.toString());
});
client.on('connect', function (connection) {
console.info(`[${clientIndex}] Client connected`);
connection.on('error', function (error) {
console.error(`[${clientIndex}] Connection error: ` + error.toString());
});
connection.on('close', function () {
console.info(`[${clientIndex}] Connection closed`);
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
});
connection.on('message', function (message) {
if (message.type === 'utf8' && clientIndex === 0) {
console.info(`[${clientIndex}] Received: "${message.utf8Data}"`);
}
});
function sendAnnouncement() {
connection.sendUTF("Hi! I am " + id)
}
function sendNumbers() {
timeoutId = null;
if (connection.connected) {
const number = Math.round(Math.random() * 0xFFFFFF);
console.info(`[${clientIndex}] Sending: ${number}`)
connection.sendUTF(number.toString());
const time = 10000 + Math.round(Math.random() * 1000) * 1000;
console.info(`[${clientIndex}] Pausing for: ${time / 1000}s`);
timeoutId = setTimeout(sendNumbers, time);
}
}
sendAnnouncement();
sendNumbers();
});
client.connect(`ws://localhost:${port}/`);
}
for (let i = 0; i < 1000; i++) {
runClient(i);
}
@EdNutting
Copy link
Author

This is an extremely simple test program.

  • It starts 1,000 websocket connections (clients) - see line 61.
  • For each connection, it generates a random identifier as "uuid-port-index"
  • It announces itself to the server after connecting using "Hi! I am [identifier]"
  • It then sends a random number
  • And then enters a timeout-based loop, sending another number at a random interval

The program detects application close and cancels the timeout, so it will shut down immediately if all connections fail. The connections are terminated "brutally" from the server, not cleanly (i.e. no "goodbye" sequence is sent to the server.)

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