Is it possible to ping a server from Javascript?

后端 未结 17 1208
礼貌的吻别
礼貌的吻别 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:44

    Ping is ICMP, but if there is any open TCP port on the remote server it could be achieved like this:

    function ping(host, port, pong) {
    
      var started = new Date().getTime();
    
      var http = new XMLHttpRequest();
    
      http.open("GET", "http://" + host + ":" + port, /*async*/true);
      http.onreadystatechange = function() {
        if (http.readyState == 4) {
          var ended = new Date().getTime();
    
          var milliseconds = ended - started;
    
          if (pong != null) {
            pong(milliseconds);
          }
        }
      };
      try {
        http.send(null);
      } catch(exception) {
        // this is expected
      }
    
    }
    

提交回复
热议问题