Created
May 21, 2023 14:51
-
-
Save EdNutting/a69b5514497fa306480a1e71c49d5956 to your computer and use it in GitHub Desktop.
NodeJS Websocket Test Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an extremely simple test program.
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.)