如何在 JavaScript 或 jQuery 中 ping 通?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8961563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:09:16  来源:igfitidea点击:

How to ping in JavaScript or jQuery?

javascriptjqueryajaxping

提问by Kivylius

I want to create a game-like ping in Javascript, just like the game Counter Strike for example. I'm doing an AJAX call to the server (MySQL) and want to calculate the time that's taken, but I'm either calculating it wrong or have the wrong idea of pinging. Here is the code I have so far:

我想在 Javascript 中创建一个类似游戏的 ping,就像游戏反恐精英一样。我正在对服务器 (MySQL) 进行 AJAX 调用并想计算所用的时间,但我要么计算错误,要么对 ping 有错误的想法。这是我到目前为止的代码:

var time_stamp = new Date;

$.ajax({ type: "POST",
    url: "server.php",
    data: {....},
    success: function(output){ 

        ping = new Date - time_stamp;

    }
}); // btw, this code works fine now for ping

The problem is that sometimes I get 0ms or 3ms. Is this okay? It seems very fast to go to server.php, connect to database, select some rows, and return some data. Yes, this is on localhost, so it should be fast, but is it meant to be this fast? Should I be calculating it at FPS, or just each call to server.php?

问题是有时我会得到 0 毫秒或 3 毫秒。这个可以吗?去server.php,连接数据库,选择一些行,并返回一些数据似乎很快。是的,这是在本地主机上,所以它应该很快,但它意味着这么快吗?我应该在 FPS 上计算它,还是只是每次调用server.php

采纳答案by Rafay

the lower response time is because by default the cacheproperty is set to true, set it to falseso that every time it goes to the server not the cache

较低的响应时间是因为默认情况下该cache属性设置为 true,将其设置为false这样每次都去服务器而不是缓存

var ping = new Date;

$.ajax({ type: "POST",
    url: "server.php",
    data: {....},
    cache:false,
    success: function(output){ 

        ping = new Date - ping;

    }
});

回答by Esailija

You will not be able to calculate accurate latency on client side (not counting java, flash or websockets), you need the server to calculate it and return the value in a response. Getting anything other than 0msfor localhost should be enough evidence of this :P

您将无法在客户端计算准确的延迟(不包括 java、flash 或 websockets),您需要服务器计算它并在响应中返回值。获得除0ms本地主机以外的任何东西应该足以证明这一点:P

The earliest time in connection state gets me 300msfor stackoverflow.com, while the real number is closer to 100ms.

连接状态的最早时间让我300msstackoverflow.com,而实际数字更接近100ms.

var a = new XMLHttpRequest();

a.onreadystatechange = function () {

    if (a.readyState === a.HEADERS_RECEIVED) {
        a.abort();
        console.log(new Date - abc);
    }
};

var abc = new Date;

a.open("GET", "/");
a.send(null);

Waiting for the full response (a.DONE) took 949ms

等待完整响应 ( a.DONE)949ms