How to determine latency of a remote server through the browser

后端 未结 9 766
暖寄归人
暖寄归人 2020-12-17 15:41

I run a couple of game tunnelling servers and would like to have a page where the client can run a ping on all the servers and find out which is the most responsive. As far

9条回答
  •  Happy的楠姐
    2020-12-17 16:28

    All you really need is the time from the connection start, to the time of the first readystate change...

    function getPing() {
      var start;
      var client = getClient(); // xmlhttprequest object
      client.onreadystatechange = function() {
        if (client.readyState > 0) {
          pingDone(start); //handle ping
          client.onreadystatechange = null; //remove handler
        } 
      }
    
      start = new Date();
      client.open("HEAD", "/ping.txt"); //static file
      client.send();
    }
    
    function pingDone(start) {
      done = new Date();
      ms = done.valueOf() - start.valueOf();
      alert(ms + "ms ping time");
    }
    
    function getClient() {
      if (window.XMLHttpRequest)
        return new XMLHttpRequest();
    
      if (window.ActiveXObject)
        return new ActiveXObject('MSXML2.XMLHTTP.3.0');
    
      throw("No XMLHttpRequest Object Available.");
    }
    

提交回复
热议问题