简体   繁体   English

如何在wifi网络中测量延迟Java Java Android

[英]How to measure latency in a wifi network java android

I am developing a mobile app, I need some parameters to implement the algorithm, and I do not know how to measure latency in a wifi network. 我正在开发一个移动应用程序,我需要一些参数来实现该算法,而且我不知道如何测量wifi网络中的延迟。 Some people says using ping, but I do not know how implement this. 有人说使用ping,但我不知道如何实现。

This is my first question, I am learning. 这是我正在学习的第一个问题。 Thank you. 谢谢。

Please have a look at this answer it might be what you are after 请看看这个答案,这可能是您想要的

you might want to try the following code sample to measure time to do something 您可能想尝试以下代码示例来衡量执行某项操作的时间

String host = "172.16.0.2";
int timeout = 3000;
long beforeTime = System.currentTimeMillis();
reachable =  InetAddress.getByName(host).isReachable(timeout);
long afterTime = System.currentTimeMillis();
long timeDifference = afterTime - beforeTime;

Here is my own implementation, hope it helps: 这是我自己的实现,希望对您有所帮助:

/*
Returns the latency to a given server in mili-seconds by issuing a ping command.
system will issue NUMBER_OF_PACKTETS ICMP Echo Request packet each having size of 56 bytes
every second, and returns the avg latency of them.
Returns 0 when there is no connection
 */
public double getLatency(String ipAddress){
    String pingCommand = "/system/bin/ping -c " + NUMBER_OF_PACKTETS + " " + ipAddress;
    String inputLine = "";
    double avgRtt = 0;

    try {
        // execute the command on the environment interface
        Process process = Runtime.getRuntime().exec(pingCommand);
        // gets the input stream to get the output of the executed command
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        inputLine = bufferedReader.readLine();
        while ((inputLine != null)) {
            if (inputLine.length() > 0 && inputLine.contains("avg")) {  // when we get to the last line of executed ping command
                break;
            }
            inputLine = bufferedReader.readLine();
        }
    }
    catch (IOException e){
        Log.v(DEBUG_TAG, "getLatency: EXCEPTION");
        e.printStackTrace();
    }

    // Extracting the average round trip time from the inputLine string
    String afterEqual = inputLine.substring(inputLine.indexOf("="), inputLine.length()).trim();
    String afterFirstSlash = afterEqual.substring(afterEqual.indexOf('/') + 1, afterEqual.length()).trim();
    String strAvgRtt = afterFirstSlash.substring(0, afterFirstSlash.indexOf('/'));
    avgRtt = Double.valueOf(strAvgRtt);

    return avgRtt;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM