Java获取服务器上行下行速率,上传下载总流量工具类

package com.wsssj.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class NetWorkUtil {
    private static final int SLEEP_TIME = 1 * 1000;

    //获取网络上行下行速度
    public static Map<String, String> getNetworkDownUp() {
        Properties props = System.getProperties();
        String os = props.getProperty("os.name").toLowerCase();
        os = os.startsWith("win") ? "windows" : "linux";
        Map<String, String> result = new HashMap<>();
        Process pro = null;
        Runtime r = Runtime.getRuntime();
        BufferedReader input = null;
        String rxPercent = "";
        String txPercent = "";
        try {
            String command = "windows".equals(os) ? "netstat -e" : "ifconfig";
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long result1[] = readInLine(input, os);
            Thread.sleep(SLEEP_TIME);
            pro.destroy();
            input.close();
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long result2[] = readInLine(input, os);
            // 上行速率(kB/s)
            rxPercent = formatNumber((result2[0] - result1[0]) / (1024.0 * (SLEEP_TIME / 1000)));
            // 下行速率(kB/s)
            txPercent = formatNumber((result2[1] - result1[1]) / (1024.0 * (SLEEP_TIME / 1000)));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Optional.ofNullable(pro).ifPresent(p -> p.destroy());
        }// 下行速率
        result.put("rxPercent", rxPercent);
        // 上行速率
        result.put("txPercent", txPercent);
        return result;

    }

    private static long[] readInLine(BufferedReader input, String osType) {
        long arr[] = new long[2];
        StringTokenizer tokenStat = null;
        try {
            // 获取linux环境下的网口上下行速率
            if ("linux".equals(osType)) {
                long rx = 0, tx = 0;
                String line = null;
                //RX packets:4171603 errors:0 dropped:0 overruns:0 frame:0
                //TX packets:4171603 errors:0 dropped:0 overruns:0 carrier:0
                while ((line = input.readLine()) != null) {
                    if (line.indexOf("RX packets") >= 0) {
                        rx += Long.parseLong(line.substring(line.indexOf("RX packets") + 11, line.indexOf(" ", line.indexOf("RX packets") + 11)));
                    } else if (line.indexOf("TX packets") >= 0) {
                        tx += Long.parseLong(line.substring(line.indexOf("TX packets") + 11, line.indexOf(" ", line.indexOf("TX packets") + 11)));
                    }
                }
                arr[0] = rx;
                arr[1] = tx;
            } else { // 获取windows环境下的网口上下行速率
                input.readLine();
                input.readLine();
                input.readLine();
                input.readLine();
                tokenStat = new StringTokenizer(input.readLine());
                tokenStat.nextToken();
                arr[0] = Long.parseLong(tokenStat.nextToken());
                arr[1] = Long.parseLong(tokenStat.nextToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arr;
    }

    private static String formatNumber(double f) {
        return new Formatter().format("%.2f", f).toString();
    }

    //获取网络总流量
    public static Map<String, Long> getTotalNetworkTraffic() {
        Properties props = System.getProperties();
        String os = props.getProperty("os.name").toLowerCase();
        os = os.startsWith("win") ? "windows" : "linux";
        Map<String, Long> result = new HashMap<>();
        Process pro = null;
        Runtime r = Runtime.getRuntime();
        BufferedReader input = null;
        try {
            String command = "windows".equals(os) ? "netstat -e" : "ifconfig";
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long[] traffic = readTotalTraffic(input, os);
            // 接收的总字节数
            result.put("rxBytes", traffic[0]);
            // 发送的总字节数
            result.put("txBytes", traffic[1]);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Optional.ofNullable(pro).ifPresent(Process::destroy);
        }
        return result;
    }

    private static long[] readTotalTraffic(BufferedReader input, String osType) {
        long[] arr = new long[2];
        try {
            if ("linux".equals(osType)) {
                long rx = 0, tx = 0;
                String line;
                while ((line = input.readLine()) != null) {
                    if (line.contains("RX bytes")) {
                        rx = Long.parseLong(line.split("RX bytes:")[1].split(" ")[0]);
                        tx = Long.parseLong(line.split("TX bytes:")[1].split(" ")[0]);
                        break;
                    }
                }
                arr[0] = rx;
                arr[1] = tx;
            } else {
                input.readLine();
                input.readLine();
                input.readLine();
                input.readLine();
                StringTokenizer tokenStat = new StringTokenizer(input.readLine());
                tokenStat.nextToken();
                arr[0] = Long.parseLong(tokenStat.nextToken());
                arr[1] = Long.parseLong(tokenStat.nextToken());

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arr;
    }

    public static void main(String[] args) {
        Map<String, String> result = getNetworkDownUp();
        Map<String, Long> totalNetworkTraffic = getTotalNetworkTraffic();
        System.out.println(result.get("rxPercent"));
        System.out.println(result.get("txPercent"));
        System.out.println(totalNetworkTraffic.get("rxBytes"));
        System.out.println(totalNetworkTraffic.get("txBytes"));

    }
}

假设有如下数据: | 手机号 | 上行流量 | 下行流量 | | ----------- | -------- | -------- | | 13926251106 | 100MB | 200MB | | 15013685858 | 50MB | 150MB | | 13560439658 | 80MB | 120MB | | 13602846565 | 60MB | 180MB | 可以将每个手机号对应的数据封装成一个对象,再将所有对象序列化成一个字符串,例如使用JSON格式: ```json [ {"phone_number": "13926251106", "uplink_flow": "100MB", "downlink_flow": "200MB"}, {"phone_number": "15013685858", "uplink_flow": "50MB", "downlink_flow": "150MB"}, {"phone_number": "13560439658", "uplink_flow": "80MB", "downlink_flow": "120MB"}, {"phone_number": "13602846565", "uplink_flow": "60MB", "downlink_flow": "180MB"} ] ``` 在计算总上行流量下行流量总流量时,可以将JSON数据反序列化为对象数组,对每个对象的上行流量下行流量进行累加,得到总上行流量、总下行流量总流量。例如,使用Python代码实现: ```python import json data = '[{"phone_number": "13926251106", "uplink_flow": "100MB", "downlink_flow": "200MB"},{"phone_number": "15013685858", "uplink_flow": "50MB", "downlink_flow": "150MB"},{"phone_number": "13560439658", "uplink_flow": "80MB", "downlink_flow": "120MB"},{"phone_number": "13602846565", "uplink_flow": "60MB", "downlink_flow": "180MB"}]' objects = json.loads(data) total_uplink = 0 total_downlink = 0 for obj in objects: uplink = int(obj["uplink_flow"].replace("MB", "")) downlink = int(obj["downlink_flow"].replace("MB", "")) total_uplink += uplink total_downlink += downlink total_flow = total_uplink + total_downlink print("总上行流量:{}MB".format(total_uplink)) print("总下行流量:{}MB".format(total_downlink)) print("总流量:{}MB".format(total_flow)) ``` 输出结果: ``` 总上行流量:290MB 总下行流量:650MB 总流量:940MB ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书写芳华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值