-
Notifications
You must be signed in to change notification settings - Fork 2
/
send.js
43 lines (40 loc) · 1.07 KB
/
send.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
const net = require('net');
const varint = require('varint');
module.exports = (ip, port, packet, timeout = 5000) => {
return new Promise(async (resolve, reject) => {
var data = Buffer.alloc(0);
var length;
var hasResponded = false;
setTimeout(() => {
if (!hasResponded) {
client.destroy();
resolve('timeout');
}
}, timeout)
const client = new net.Socket();
client.connect(port, ip, () => client.write(packet));
client.on('error', err => {
client.destroy();
resolve(err.toString());
});
client.on('data', newData => {
if (data.length == 0) {
try {
length = varint.decode(newData);
newData = newData.subarray(varint.decode.bytes);
} catch (error) {
length = 0;
newData = Buffer.alloc(0);
client.destroy();
}
}
data = Buffer.concat([data, newData]);
if (data.length >= length) {
data = data.subarray(0, length);
hasResponded = true;
client.destroy();
resolve(data);
}
})
})
}