2014年12月19日 星期五

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

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

沒有留言:

張貼留言