我一直在爲自己和一些朋友開發一個聊天客戶端,並決定嘗試添加功能以允許客戶端之間的文件傳輸。我能夠發送一個文件,但它到達的狀態與發送的文件不同。作爲一個例子,這裏是之前發送的圖像之後比較鏈接:使用Java套接字和DataStream進行文件傳輸的問題
http://i.imgur.com/qbMo0gy.png
不要問爲什麼我使用的圖片,這只是第一個我在圖片文件夾中找到.. 。 而且這裏的發送和接收方法:
public static Runnable sendFile(String target, File file, Client client) {
Runnable run =() -> {
FileOutputStream fileOut = null;
try {
int total = 0;
int count;
byte[] fileBuffer = new byte[8192];
BufferedInputStream fileStream = new BufferedInputStream(new FileInputStream(file));
client.getTextOutData().writeUTF("*!sendfile: " + client.getClientName() + " " + target + " " + file.getName() + " " + (int) file.length());
fileOut = new FileOutputStream(new File(downloadsPath + "/" + file.getName()));
System.out.println("Send length: " + file.length());
while ((count = fileStream.read(fileBuffer, 0, (int) Math.min(8192, file.length() - total))) == 8192) {
total += count;
System.out.println("Sender count: " + count);
client.getDLOutData().write(fileBuffer, 0, count);
client.getDLOutData().flush();
fileOut.write(fileBuffer, 0, count);
}
total += count;
System.out.println("Sender count: " + count);
System.out.println("Sender total: " + total);
//client.getDLOutData().write(fileBuffer, 0, count);
fileOut.write(fileBuffer, 0, count);
System.out.println("Sending done, eh?");
fileStream.close();
Thread.currentThread().interrupt();
} catch (Exception e) {
Platform.runLater(() ->Popups.startInfoDlg("Download Error", "Failed to send file!"));
e.printStackTrace();
}
};
return run;
}
public static Runnable dlFile(MainScreenController sc, File file, long length) {
Runnable run =() -> {
FileOutputStream fileOut = null;
try {
int total = 0;
int count;
byte[] fileBuffer = new byte[8192];
fileOut = new FileOutputStream(file);
System.out.println("DL length: " + length);
while ((count = sc.getClient().getDLInData().read(fileBuffer, 0, (int) Math.min(8192, length - total))) == 8192){
total += count;
System.out.println("DL count: " + count);
fileOut.write(fileBuffer, 0, count);
}
total += count;
System.out.println("DL count: " + count);
System.out.println("DL total: " + total);
//fileOut.write(fileBuffer, 0, count);
} catch (IOException e) {
System.out.println("Failed to download file.");
e.printStackTrace();
} finally {
try {
fileOut.flush();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Download complete.");
Thread.currentThread().interrupt();
}
};
return run;
}
如果你有任何想法是什麼問題,我很樂意聽到他們的聲音。如果您需要更多幫助,我也可以嘗試爲整個項目設置Git。任何幫助表示讚賞,我還剛剛開始學習java。
不要將您的代碼發佈到pastebin。它必須在問題本身。 –
@Ben - 剛纔看看你的代碼sendFile方法,在while循環中你的偏移量總是0.我覺得這不應該是這樣的。它會不會覆蓋上一次迭代中讀取的一些字節?希望我沒有錯! – Ouney
你的代碼很麻煩,單獨發送最後一個塊是什麼,但我認爲它應該工作。你能否測試兩個文件的確切大小(以字節爲單位)?我在想也許這是一個PNG可移植性問題,我讀過它有「Gamma校正」和「Alpha透明度」的問題,它在不同系統上顯示不同。這可以通過將'錯誤'圖像複製回原始系統(例如通過鑰匙上的磁盤)並檢查它的外觀來驗證。 –