Ping a server in javascript
by Christopher O
HTML
<ul data-bind="foreach:servers">
<li> <a href="#" data-bind="text:name,attr:{href: 'http://'+name}">tester</a> <span data-bind="text:status,css:status"></span>
</li>
</ul>
CSS
.responded {
color:green;
}
.checking,.unchecked {
color:#FF8C00;
}
.timeout {
color:red;
}
}
JavaScript
// maybe not 'ping exactly' but seems to work
// https://stackoverflow.com/questions/4282151/is-it-possible-to-ping-a-server-from-javascript
function ping(ip, callback) {
if (!this.inUse) {
this.status = 'unchecked';
this.inUse = true;
this.callback = callback;
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function () {
_that.inUse = false;
_that.callback('responded');
};
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('responded', e);
}
};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 1500);
}
}
var PingModel = function (servers) {
var self = this;
var myServers = [];
ko.utils.arrayForEach(servers, function (location) {
myServers.push({
name: location,
status: ko.observable('unchecked')
});
});
self.servers = ko.observableArray(myServers);
ko.utils.arrayForEach(self.servers(), function (s) {
s.starttime = new Date().getTime();
s.status('checking');
new ping(s.name, function (status, e) {
const now = new Date().getTime();
s.status(status + " " + (now - s.starttime) + "ms");
});
});
};
var komodel = new PingModel(['localhost',
'https://wikipedia.org',
'ws-bdimperio8.payformance.net',
'ws-bdimperio8.payformance.com',
'//jsfiddle.net/echo/jsonp/',
'ws-bdimperio8/favicon.ico',
'127.0.0.1',
'unknown',
'https://modernsaas.net:11114/ping',
...