我正在编写一个小的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");
这是因为我正在使用自己的缓冲区来减慢所有速度,还是可能是问题所在?提示与技巧提示也很受欢迎.