gpt4 book ai didi

android TrafficStats getUidRxBytes 不准确

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:31 28 4
gpt4 key购买 nike

我写了一个小的 android 应用程序,发送 Http 请求,从服务器接收响应,并计算传输和接收的字节数。代码如下

long receivedBytes = TrafficStats.getUidRxBytes(uid)-lastNumer

我发现 receivedBytes 总是大于 http Header+http Body 的大小,例如我在服务器中捕获(使用 wireshark)的实际 http 帧大小为 1645 字节( header +正文),但 android API 返回 receivedBytes 为 1912,因此传输。

TrafficStats getUidRxBytes 本身不准确(可能这个问题是我的平台 samsung i9300 和 cynogenmod 10.3 特有的)

最后,我找到了计算数据使用量的正确方法我找到了其他方法来计算数据使用量,这似乎比 TrafficStats API 更准确。(非常感谢 here)

private long[] getStat() {
String line, line2;
long[] stats = new long[2];
try {
File fileSnd = new File("/proc/uid_stat/"+uid+"/tcp_snd");
File fileRcv = new File ("/proc/uid_stat/"+uid+"/tcp_rcv");
BufferedReader br1 = new BufferedReader(new FileReader(fileSnd));
BufferedReader br2 = new BufferedReader(new FileReader(fileRcv));
while ((line = br1.readLine()) != null&& (line2 = br2.readLine()) != null) {
stats[0] = Long.parseLong(line);
stats[1] = Long.parseLong(line2);
}
br1.close();
br2.close();
} catch (Exception e) {
e.printStackTrace();
}
return stats;
}

最佳答案

我看到您已经找到了解决方案,但我会在您的问题上添加我的想法,因为它可能对其他人有用(在谷歌搜索如何使用 TrafficStats API 后,我自己最终来到这里)。

API documentation状态:

Statistics are measured at the network layer, so they include both TCP and UDP usage.

文档确实可以更详尽,但我倾向于说可以假设返回的字节数还包括构成传输层 header 和网络层 header 的字节

HTTP is an application layer protocol .当您将预期字节计算为 HTTP header 字节加上 HTTP 正文字节时,您只处理应用程序层字节,因此不考虑传输层和网络层 header 字节。我假设 TCP 用于下载。 This adds a header ranging from 20 to 60 bytes .此外,假设您使用 IPv4 进行下载。 This also adds a header ranging from 20 to 60 bytes .

显然这不会占整个 1912 - 1645 = 267 字节,但它可能会给你/其他人一些线索。


有点离题,但还是相关的。目前尚不清楚 TrafficStats API 是否实际计算 header 字节数。根据this answer , API 计算 header 字节。但是,考虑到上面列出的 API 文档,链接的答案可能规定了不正确的内容(至少对于 API 级别 21 而言并非如此)。此外,this question还暗示 TrafficStats 实际上在计算网络和传输层 header 字节(查看评论)。


TrafficStats 实际上计算网络和传输层 header 字节。参见 kernel sourceTrafficStatsTest .

关于android TrafficStats getUidRxBytes 不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25440796/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com