我正在编写一个可以测量本地网络速度的小型 Java 程序。这是我第一次使用套接字,但我已经编写了一个可以工作的程序。唯一的问题是测量结果远非准确(太低了)。
这是服务器代码:
ServerSocket servsock = new ServerSocket(13267);
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
File myFile = new File("test.txt");
FileInputStream in = new FileInputStream(myFile);
OutputStream out = sock.getOutputStream();
int bytes = 0;
byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
bytes += len;
}
System.out.println("Transfer completed, " + bytes + " bytes sent");
out.flush();
sock.close();
}
这是客户端代码:
Socket sock = new Socket("192.168.0.100", 13267);
System.out.println("Connecting to : " + sock);
InputStream in = sock.getInputStream();
FileOutputStream out = new FileOutputStream("received.txt");
int bytes = 0;
byte[] buffer = new byte[8192];
int len;
long start = System.currentTimeMillis();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
bytes += len;
}
long end = System.currentTimeMillis();
out.close();
sock.close();
double kbps = (bytes / 1000) / ((end - start) / 1000);
System.out.println("Speed: " + kbps + " kbps");
这是因为我正在使用我自己的缓冲区,这会减慢一切,或者可能是什么问题?也欢迎提示和提示。