在 Java 中“测试网络性能”通常分为几种场景:单机/局域网带宽测试、延迟测试、TCP/UDP 吞吐测试、以及基于 Java 的网络压测工具。下面按常用方法和示例代码系统说明。
ServerSocket server = new ServerSocket(9000);
Socket socket = server.accept();
InputStream in = socket.getInputStream();
byte[] buf = new byte[8192];
long total = 0;
long start = System.currentTimeMillis();
while (true) {
int len = in.read(buf);
if (len == -1) break;
total += len;
}
long end = System.currentTimeMillis();
System.out.println("Received: " + total + " bytes");
System.out.println("Time: " + (end - start) + " ms");
System.out.println("Speed: " + (total * 1000.0 / (end - start) / 1024 / 1024) + " MB/s");
Socket socket = new Socket("127.0.0.1", 9000);
OutputStream out = socket.getOutputStream();
byte[] data = new byte[8192];
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
out.write(data);
}
out.flush();
long end = System.currentTimeMillis();
System.out.println("Send time: " + (end - start) + " ms");
✅ 适合测试:
Process p = Runtime.getRuntime().exec("ping -c 4 8.8.8.8");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
⚠️ 依赖操作系统(Linux / Windows 参数不同)
long start = System.nanoTime();
Socket s = new Socket("example.com", 80);
long end = System.nanoTime();
System.out.println("Connect time: " + (end - start) / 1_000_000 + " ms");
s.close();
DatagramSocket socket = new DatagramSocket();
InetAddress addr = InetAddress.getByName("127.0.0.1");
byte[] data = new byte[1024];
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
socket.send(new DatagramPacket(data, data.length, addr, 9000));
}
long end = System.currentTimeMillis();
System.out.println("UDP send speed: " + (10000*1024*1000L/(end-start)/1024/1024) + " MB/s");
iperf -s
iperf -c 192.168.1.10
| 指标 | 含义 |
|---|---|
| 带宽 | MB/s |
| 延迟 | ms |
| 丢包率 | UDP |
| 连接数 | 并发能力 |
| RTT | 往返时间 |
BufferedOutputStreamflush()如果你愿意,可以告诉我:
我可以直接给你一份可运行的完整测试程序。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。