【问题标题】:How to measure latency in a wifi network java android如何测量wifi网络中的延迟java android
【发布时间】:2014-06-09 11:28:21
【问题描述】:

我正在开发一个移动应用程序,我需要一些参数来实现算法,但我不知道如何测量 wifi 网络中的延迟。有人说用ping,不知道怎么实现。

这是我的第一个问题,我正在学习。 谢谢。

【问题讨论】:

  • 发布你到目前为止所尝试的内容。

标签: java android wifi android-wifi latency


【解决方案1】:

请看this answer,这可能是你想要的

您可能想尝试以下代码示例来衡量做某事的时间

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;

【讨论】:

  • 这必须在单独的线程上完成,因为网络执行不能在主线程上完成。
【解决方案2】:

这是我自己的实现,希望对你有帮助:

/*
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;
}

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2012-07-04
    • 2020-09-22
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2021-06-08
    • 1970-01-01
    相关资源
    最近更新 更多