Question

I've made this ping.js script but i seem to be getting quite a high ping even though when i ping from CMD i get a much lower ping. If there is anyway i'm able to show the true ping instead of it being much higher that would be appreciated.

    function colorcode(ms){
    if (ms < 65) {return "#8bc53f";
    } else if ((ms >= 65) && (ms < 160)) { return "#f26522";
    } else if ((ms >= 160) && (ms < 400)) { return "#ed1c24";
    } else if ((ms >= 400) && (ms < 1000)) { return "#ed1c24";
    } else { return "#232323"; }

}

function output_text(txt,id){
    txt = Math.round((3/4)*txt);
    var obj = document.getElementById(id);
    var txt_ = "<font color='"+colorcode(parseInt(txt))+"'>"+((parseInt(txt)<1000)?txt+"</font> ms":"Offline</font>");
    obj.innerHTML=txt_;
}

function reping() {
i = 2;
for(var id in idips){
setTimeout("ping2('"+id+"','"+idips[id]+"',"+(i*2+1)+")",i);
i += 100;
}}

var idips = new Array();

function ping(id,ip,i){
    document.write("<span id='"+id+"'>pinging server...</span>");
    setTimeout("ping2('"+id+"','"+ip+"',"+i+")",(i+2)*100);
    idips[id] = ip;
}

function koekjes(){
var koekje = new Array('k','o','e','j','w','s');
var koek = new Array();
var rd = new Array();
var koekz = '';
var rd = new Array();
for(i=0;i<=21;i++){
rd[i] = Math.floor(Math.random()*koekje.length);
koekz += koekje[rd[i]];
}
return koekz
}

function ping2(id,ip,i) {
    var ImageObject = new Image();
    ImageObject.onerror = function(evt){ var endTime = new Date(); output_text(endTime-startTime,id);}
    ImageObject.onload = function(evt){ var endTime = new Date(); output_text(endTime-startTime,id);}
    var startTime = new Date();
    ImageObject.src = "http://"+ip+"/"+koekjes()+".gif";
}

Thanks.

Was it helpful?

Solution

You measure the latency between sending a request, and getting an answer.

The command line program ping uses an ICMP packet for that, you use an HTTP request.

An HTTP request needs to establish a TCP connect, sending the the request (HTTP is quite chatty), parsing the request, handling the request, sending the response, and parsing the response.

But the major problem is the handshake, which makes the request three times slower.

To get the real latency you cannot use time / 3, because the connection could be kept alive, in which case there is no handshake.

To summarize: don't use HTTP/TCP to measure the latency.


Edit:

You can just connect to a closed port, like 3 or 4. In this case the connection attempt (TCP syn) gets rejected by the server. (Syn is the first part in a TCP handshake.)

Online demo: http://jsfiddle.net/wDz38/.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top