Is it possible to ping a server from Javascript?

后端 未结 17 923
礼貌的吻别
礼貌的吻别 2020-11-22 04:02

I\'m making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 e

17条回答
  •  心在旅途
    2020-11-22 04:35

    I have found someone that accomplishes this with a very clever usage of the native Image object.

    From their source, this is the main function (it has dependences on other parts of the source but you get the idea).

    function Pinger_ping(ip, callback) {
    
      if(!this.inUse) {
    
        this.inUse = true;
        this.callback = callback
        this.ip = ip;
    
        var _that = this;
    
        this.img = new Image();
    
        this.img.onload = function() {_that.good();};
        this.img.onerror = function() {_that.good();};
    
        this.start = new Date().getTime();
        this.img.src = "http://" + ip;
        this.timer = setTimeout(function() { _that.bad();}, 1500);
    
      }
    }
    

    This works on all types of servers that I've tested (web servers, ftp servers, and game servers). It also works with ports. If anyone encounters a use case that fails, please post in the comments and I will update my answer.

    Update: Previous link has been removed. If anyone finds or implements the above, please comment and I'll add it into the answer.

    Update 2: @trante was nice enough to provide a jsFiddle.

    http://jsfiddle.net/GSSCD/203/

    Update 3: @Jonathon created a GitHub repo with the implementation.

    https://github.com/jdfreder/pingjs

    Update 4: It looks as if this implementation is no longer reliable. People are also reporting that Chrome no longer supports it all, throwing a net::ERR_NAME_NOT_RESOLVED error. If someone can verify an alternate solution I will put that as the accepted answer.

提交回复
热议问题