-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudpClient.js
46 lines (41 loc) · 1.22 KB
/
udpClient.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
const chalk = require('chalk');
const dgram = require('dgram');
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 udpClient(options) {
const {host, port, repeats, data, interval, verbose, quiet} = options;
const client = dgram.createSocket('udp4');
if (verbose) {
client.on('message',function(msg,info){
console.log(`Received ${msg.length}-byte reply from ${info.address}:${info.port}: ${msg.toString()}`);
});
}
let timer = setInterval(() => {
let message = data || `Message #${count+1}.`;
let text = Buffer.from(message);
client.send(text, port, host, (error) => {
count++;
bytes += text.length;
if (error) {
errors++;
if (!quiet) {
console.log(chalk.red("Error on send:"), err);
}
} else { // success
if (verbose) {
reportStats('Sent ');
}
}
});
if ((repeats > 0) && (count >= repeats)) {
clearInterval(timer);
client.close();
reportStats('Test complete: sent ');
}
}, interval*1000);
}
module.exports = { udpClient };