• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 统计网络流量消耗
2<!--Kit: Network Kit-->
3<!--Subsystem: Communication-->
4<!--Owner: @wmyao_mm-->
5<!--Designer: @guo-min_net-->
6<!--Tester: @tongxilin-->
7<!--Adviser: @zhang_yixin13-->
8
9## 简介
10
11流量管理提供了基于物理网络的数据流量统计能力,支持基于网卡/UID 的流量统计。
12
13流量管理主要实现功能有:
14
15- 支持基于网卡/UID 的实时流量统计。
16- 支持基于网卡/UID 的历史流量统计。
17- 支持基于网卡/UID 的流量变化订阅。
18
19> **说明:**
20> 为了保证应用的运行效率,大部分 API 调用都是异步的,对于异步调用的 API 均提供了 callback 和 Promise 两种方式,以下示例均采用 Promise 函数,更多方式可以查阅[API 参考](../reference/apis-network-kit/js-apis-net-statistics.md)。
21
22以下分别介绍具体开发方式。
23
24## 开发步骤
25
261. 导入statistics、socket以及错误码模块。
27
28    ```ts
29    import { statistics, socket } from '@kit.NetworkKit';
30    import { BusinessError } from '@kit.BasicServicesKit';
31    ```
32
332. 获取指定网卡实时流量数据
34
35    调用getIfaceRxBytes接口传入网卡名获取实时下行流量数据。
36
37    ```ts
38    // wlan0为主WiFi网卡名,获取主WiFi实时下行流量数据。
39    statistics.getIfaceRxBytes("wlan0").then((stats: number) => {
40      console.log(JSON.stringify(stats));
41    });
42
43    // wlan0为主WiFi网卡名,获取主WiFi实时上行流量数据。
44    statistics.getIfaceTxBytes("wlan0").then((stats: number) => {
45      console.log(JSON.stringify(stats));
46    });
47    ```
48
493. 获取蜂窝实时流量数据
50
51    调用getCellularRxBytes接口获取蜂窝实时上下行流量数据。
52
53    ```ts
54    // 获取蜂窝实时下行流量数据。
55    statistics.getCellularRxBytes().then((stats: number) => {
56      console.log(JSON.stringify(stats));
57    });
58
59    // 获取蜂窝实时上行流量数据。
60    statistics.getCellularTxBytes().then((stats: number) => {
61      console.log(JSON.stringify(stats));
62    });
63    ```
64
654. 获取所有网卡实时流量数据
66
67    调用getAllRxBytes接口获取所有网卡实时上下行流量数据。
68
69    ```ts
70    // 获取所有网卡实时下行流量数据。
71    statistics.getAllRxBytes().then((stats: number) => {
72      console.log(JSON.stringify(stats));
73    });
74
75    // 获取所有网卡实时上行流量数据。
76    statistics.getAllTxBytes().then((stats: number) => {
77      console.log(JSON.stringify(stats));
78    });
79    ```
80
815. 获取指定应用实时流量数据
82
83    调用getUidRxBytes接口,传入UID获取指定应用实时上下行流量数据。
84
85    ```ts
86    // 获取指定应用实时下行流量数据。
87    let uid = 20010038;
88    statistics.getUidRxBytes(uid).then((stats: number) => {
89      console.log(JSON.stringify(stats));
90    });
91
92    // 获取指定应用实时上行流量数据。
93    let uid = 20010038;
94    statistics.getUidTxBytes(uid).then((stats: number) => {
95      console.log(JSON.stringify(stats));
96    });
97    ```
98
996. 获取指定socket实时流量数据
100
101    调用getSockfdRxBytes接口,传入指定的sockFd获取指定socket实时上下行流量数据。
102
103    ```ts
104    // 获取指定socket实时下行流量数据。
105    let tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
106    tcp.getSocketFd().then((sockfd: number) => {
107      statistics.getSockfdRxBytes(sockfd).then((stats: number) => {
108        console.log(JSON.stringify(stats));
109      }).catch((err: BusinessError) => {
110        console.error(JSON.stringify(err));
111      });
112    });
113
114    // 获取指定socket实时上行流量数据。
115    tcp.getSocketFd().then((sockfd: number) => {
116      statistics.getSockfdTxBytes(sockfd).then((stats: number) => {
117        console.log(JSON.stringify(stats));
118      }).catch((err: BusinessError) => {
119        console.error(JSON.stringify(err));
120      });
121    });
122    ```
123
124<!--Del-->
125## 获取网卡/UID 的历史流量统计数据
126
1271. 获取指定网卡历史流量信息。
1282. 获取指定应用历史流量信息。
129
130```ts
131import { statistics } from '@kit.NetworkKit';
132import { BusinessError } from '@kit.BasicServicesKit';
133
134class IfaceInfo {
135  iface: string = "wlan0"
136  startTime: number = 1685948465
137  endTime: number = 16859485670
138}
139// 获取指定网卡历史流量信息。
140statistics.getTrafficStatsByIface(new IfaceInfo()).then((statsInfo: statistics.NetStatsInfo) => {
141  console.log(
142    "getTrafficStatsByIface bytes of received = " +
143    JSON.stringify(statsInfo.rxBytes)
144  );
145  console.log(
146    "getTrafficStatsByIface bytes of sent = " +
147    JSON.stringify(statsInfo.txBytes)
148  );
149  console.log(
150    "getTrafficStatsByIface packets of received = " +
151    JSON.stringify(statsInfo.rxPackets)
152  );
153  console.log(
154    "getTrafficStatsByIface packets of sent = " +
155    JSON.stringify(statsInfo.txPackets)
156  );
157});
158
159class UidInfo {
160  uid: number = 20010037
161  ifaceInfo: IfaceInfo = new IfaceInfo()
162}
163
164let uidInfo = new UidInfo()
165
166// 获取指定应用历史流量信息。
167statistics.getTrafficStatsByUid(uidInfo).then((statsInfo: statistics.NetStatsInfo) => {
168  console.log("getTrafficStatsByUid bytes of received = " + JSON.stringify(statsInfo.rxBytes));
169  console.log("getTrafficStatsByUid bytes of sent = " + JSON.stringify(statsInfo.txBytes));
170  console.log("getTrafficStatsByUid packets of received = " + JSON.stringify(statsInfo.rxPackets));
171  console.log("getTrafficStatsByUid packets of sent = " + JSON.stringify(statsInfo.txPackets));
172})
173```
174
175## 订阅流量变化事件
176
1771. 订阅流量改变事件通知。
1782. 取消订阅流量改变事件通知。
179
180```ts
181import { statistics } from '@kit.NetworkKit';
182
183class Data {
184  iface: string = ""
185  uid?: number = 0
186}
187
188let callback = (data: Data) => {
189  console.log('on netStatsChange, data:' + JSON.stringify(data));
190};
191// 订阅流量改变事件通知。
192statistics.on('netStatsChange', callback);
193
194// 取消订阅流量改变事件通知。可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。
195statistics.off('netStatsChange', callback);
196statistics.off('netStatsChange');
197```
198<!--DelEnd-->
199
200## 相关实例
201
202针对流量管理的开发,有以下相关实例可供参考:
203
204- [流量管理](https://gitcode.com/openharmony/applications_app_samples/tree/master/code/DocsSample/NetWork_Kit/NetWorkKit_NetManager/FlowManagement_case)
205