-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpClient.js
55 lines (49 loc) · 1.47 KB
/
tcpClient.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const chalk = require('chalk');
const net = require('net');
let count = 0;
let bytes = 0;
let errors = 0;
function reportStats(prefix) {
console.log(prefix+`${chalk.blueBright(''+bytes)} bytes, in ${chalk.green(''+count)} messages, ${chalk.red(errors)} errors.`);
}
function tcpClient(options) {
const {host, port, repeats, interval, data, verbose, quiet} = options;
const client = new net.Socket();
console.log(`Connecting to ${host}:${port}...`);
client.connect(port, host);
client.on('end', () => {
console.log(chalk.yellow(`Disconnected from ${host}:${port}.`));
});
client.on('connect', () => {
console.log(chalk.green(`Connected to ${host}:${port}. Sending data.`));
client.setEncoding('utf8');
let timer = setInterval(() => {
let myNum = count+1;
if ((repeats > 0) && (myNum > repeats)) {
clearInterval(timer);
client.end(() => {
reportStats('Test complete: sent ');
process.exit(0);
});
return;
}
let message = data || `Message #${myNum}.`;
var text = Buffer.from(message);
client.write(text, (err) => {
count++;
bytes += text.length;
if (err) {
errors++;
if (!quiet) {
console.log(chalk.red("Error on send:"), err);
}
} else { // success
if (verbose) {
reportStats('Sent ');
}
}
});
}, interval*1000);
});
}
module.exports = { tcpClient };