2014年12月19日 星期五

javascript去檢測(類似ping)區網有無這個ip

http://stackoverflow.com/questions/4282151/is-it-possible-to-ping-a-server-from-javascript
修改後:
ping = function(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);
 }
};

//使用:
new ping('192.168.0.88', function(status, e) {
 console.log(status);
});

有這個ip,在控制台會顯示 responded,沒有則會顯示timeout

沒有留言:

張貼留言