闲来无事,逛一论坛时,发现一段有趣的代码,我做了点小小的改动,发现可以用js可以实现ping一个主机的方法,不得不感叹js真是强大啊,先贴出代码如下:
function testPing(ip) {
var img = new Image();
var start = new Date().getTime();
var flag = false;
var isWifiWork = true;
var hasComplete = false;
img.onload = function() {
if (!hasComplete) {
flag = true;
hasComplete = true;
console.log('Ping:' + ip + ' successful.');
}
};
img.onerror = function() {
if (!hasComplete) {
if (!isWifiWork) {
flag = true;
console.log('Ping:' + ip + ' successful.');
} else {
console.log('The network is not working!');
}
hasComplete = true;
}
};
setTimeout(function(){
isWifiWork = false;
console.log('The network is working, start ping...');
},2);
img.src = 'http://' + ip + '/' + start;
var timer = setTimeout(function() {
if (!flag) {
hasComplete = true;
flag = false ;
console.log('Ping:' + ip + ' fail. ');
}
}, 1500);
}
testPing('www.163.com:80');
运行的效果如图:
原代码如下:
function ping(ip){
var img = new Image();
var start = new Date().getTime();
img.src = "http://"+ip+"?t="+start;
var flag = false;
img.onload = function(){
flag = true;
console.log('ok');
};
img.onerror = function(){
flag = true;
console.log('ok');
};
var timer = setTimeout(function(){
if(!flag){
flag = false;
console.log('failed');
}
},1500);
}