main.js
1.7 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class IpHunter {
constructor(ips, callback, timeout) {
this.version="v2.0.1.20170819"
this.ip = '';
this.ipcallback = callback;
this.timeoutId = null;
this.reqsCache = [];
for (let i = 0; i < ips.length; i++) {
//this.reqsCache.push(this.send(ips[i], timeout - 10));
this.reqsCache.push(this.send(ips[i], timeout));
}
this.timeoutId = setTimeout(this.notify.bind(this), timeout);
}
clearAll() {
if (this.reqsCache && this.reqsCache.length) {
this.reqsCache.forEach((req) => {
req.abort();
})
}
clearTimeout(this.timeoutId);
this.ip = '';
this.ipcallback = null;
this.timeoutId = null;
this.reqsCache = [];
}
clearReq(req) {
this.reqsCache.splice(this.reqsCache.indexOf(req), 1);
}
notify() {
if(this.ipcallback){
this.ipcallback(this.ip);
}
this.clearAll();
}
send(pip, timeout) {
const req = new XMLHttpRequest();
req.open('HEAD', `//${pip}/?_=${Date.now()}`);
req.timeout = timeout;
req.onload = () => {
this.ip = pip;
this.clearReq(req);
req.onload = null;
this.notify();
}
req.ontimeout = () => {
this.clearReq(req);
req.ontimeout = null;
}
req.onerror = () => {
this.clearReq(req);
req.onerror = null;
}
req.onabort = () => {
this.clearReq(req);
req.onabort = null;
}
req.send();
return req
}
}
/**
* ips check
* @param {array} ips
* @param {number} callback
* @return {null}
*/
export default function check(ips, callback, timeout = 3000) {
if (!(ips && ips.length && callback)) throw new Error('ips and callback are required.');
new IpHunter(ips, callback, timeout);
}