我在寫一個可以測量本地網絡速度的小型java程序。這是我第一次使用套接字工作,但我已經制定了一個可行的程序。唯一的問題是測量結果不準確(太低)。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");
這是因爲我用我自己的緩衝區的工作,一切都慢下來或可能是什麼問題?也歡迎提示&提示。
謝謝你的答案,你如何發送空白數據? – Jens
@Jens,我已將它添加到我的答案中。;) –