Is it possible to ping a server from Javascript?

后端 未结 17 901
礼貌的吻别
礼貌的吻别 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
      }
    
    }
    

    0 讨论(0)
  • 2020-11-22 04:46

    You can't directly "ping" in javascript. There may be a few other ways:

    • Ajax
    • Using a java applet with isReachable
    • Writing a serverside script which pings and using AJAX to communicate to your serversidescript
    • You might also be able to ping in flash (actionscript)
    0 讨论(0)
  • 2020-11-22 04:46
    const ping = (url, timeout = 6000) => {
      return new Promise((reslove, reject) => {
        const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]');
        if (!urlRule.test(url)) reject('invalid url');
        try {
          fetch(url)
            .then(() => reslove(true))
            .catch(() => reslove(false));
          setTimeout(() => {
            reslove(false);
          }, timeout);
        } catch (e) {
          reject(e);
        }
      });
    };
    

    use like this:

    ping('https://stackoverflow.com/')
      .then(res=>console.log(res))
      .catch(e=>console.log(e))
    
    0 讨论(0)
  • 2020-11-22 04:47

    I don't know what version of Ruby you're running, but have you tried implementing ping for ruby instead of javascript? http://raa.ruby-lang.org/project/net-ping/

    0 讨论(0)
  • 2020-11-22 04:48

    You could try using PHP in your web page...something like this:

    <html><body>
    <form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <h1>Host to ping:</h1>
    <input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
    <input type="submit" name="submit" value="Submit" >
    </form></body>
    </html>
    <?php
    
    $tgt_host = $_POST['tgt_host'];
    $output = shell_exec('ping -c 10 '. $tgt_host.');
    
    echo "<html><body style=\"background-color:#0080c0\">
    <script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
    </body></html>";
    
    ?>
    

    This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...

    0 讨论(0)
  • 2020-11-22 04:49

    If what you are trying to see is whether the server "exists", you can use the following:

    function isValidURL(url) {
        var encodedURL = encodeURIComponent(url);
        var isValid = false;
    
        $.ajax({
          url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
          type: "get",
          async: false,
          dataType: "json",
          success: function(data) {
            isValid = data.query.results != null;
          },
          error: function(){
            isValid = false;
          }
        });
    
        return isValid;
    }
    

    This will return a true/false indication whether the server exists.

    If you want response time, a slight modification will do:

    function ping(url) {
        var encodedURL = encodeURIComponent(url);
        var startDate = new Date();
        var endDate = null;
        $.ajax({
          url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
          type: "get",
          async: false,
          dataType: "json",
          success: function(data) {
            if (data.query.results != null) {
                endDate = new Date();
            } else {
                endDate = null;
            }
          },
          error: function(){
            endDate = null;
          }
        });
    
        if (endDate == null) {
            throw "Not responsive...";
        }
    
        return endDate.getTime() - startDate.getTime();
    }
    

    The usage is then trivial:

    var isValid = isValidURL("http://example.com");
    alert(isValid ? "Valid URL!!!" : "Damn...");
    

    Or:

    var responseInMillis = ping("example.com");
    alert(responseInMillis);
    
    0 讨论(0)
提交回复
热议问题