Skip to content

Instantly share code, notes, and snippets.

@clockworkgr
Created March 30, 2019 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clockworkgr/40bc1c102b3d870165dca1d9a1ad44f9 to your computer and use it in GitHub Desktop.
Save clockworkgr/40bc1c102b3d870165dca1d9a1ad44f9 to your computer and use it in GitHub Desktop.
import WebSocket from "ws";
class Pinger {
constructor(timeout, frequency) {
this.url = {};
this.urls = [];
this.timeout = timeout;
this.frequency = frequency;
let self = this;
this.check = setTimeout(() => {
this._runCheck(self)
}, this.frequency);
}
addURL(url) {
this.urls.push({
url: url,
latency: 1000
});
}
getBest() {
return this.url;
}
_checkURL(url) {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve(1000);
}, this.timeout);
try {
let connection = new WebSocket(url);
connection.openTime = process.hrtime();
connection.onerror = (error) => {
resolve(1000);
};
connection.onopen = () => {
connection.onmessage = function () {
this.closeTime = process.hrtime(this.openTime);
connection.close();
resolve(Number(this.closeTime[0] + '.' + this.closeTime[1]));
};
connection.onmessage.bind(connection);
connection.send('{"id":1,"method":"call","params":[1,"login",["",""]]}');
};
} catch (e) {
resolve(1000);
}
});
}
async _runCheck() {
for (let i = 0; i < this.urls.length; i++) {
this.urls[i].latency = this._checkURL(this.urls[i].url);
this.urls[i].latency.then(res => {
this.urls[i].latency = res;
});
}
await Promise.all(this.urls.map(x => {
return x.latency;
}));
this.urls.sort((a, b) => {
return Number(a.latency) - Number(b.latency);
});
this.url = this.urls[0];
console.log(this.urls);
console.log(this.url);
let self = this;
this.check = setTimeout(() => {
this._runCheck(self)
}, this.frequency);
}
}
let pinger = new Pinger(2000, 5000);
/* Add nodes as needed */
// pinger.addURL(node.url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment