我正在嘗試通過陣列將檔案以塊的形式從客戶端發送到服務器byte。我正在使用ObjectInputStream. 寫入作業并且檔案大小匹配,但是當我打開檔案時,我只得到一個空白文本檔案(在 IDE 中打開時,顯示NUL,NUL,NUL...)。
服務器代碼:
try(
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
){
byte[] arr = new byte[chunkSize];
try {
int len = 0;
long bytesRead = 0;
byte[] bytes = new byte[chunkSize];
int chunkNo = 1;
while(true)
{
len = in.read(bytes,0, chunkSize);
System.out.println();
if(len < 0)
break;
fileOut.write(arr, 0, len);
bytesRead = len;
out.writeObject(Server.CHUNK_ACKNOWLEDGE_MSG);
String ackReply = (String) in.readObject();
if(ackReply.equalsIgnoreCase((Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG))){
if(Server.DEBUG)
System.out.println(fileName " send timeout.");
deleteFile();
break;
}else if (ackReply.equalsIgnoreCase(Server.UPLOAD_COMPLETE_MSG)){
if(bytesRead != fileSize){
System.out.println(fileName " File size mismatch");
deleteFile();
break;
}else{
System.out.println( fileName " File written");
break;
}
}
}
}catch (IOException ioe){
if(Server.DEBUG)
ioe.printStackTrace();
}
客戶端代碼:
try(
FileInputStream fileInput = new FileInputStream(file);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
){
byte[] arr = new byte[chunkSize];
try {
int len = 0;
int bytesRead = 0;
int chunkCount = 1;
while((len = fileInput.read(arr, 0, chunkSize)) != -1)
{
out.write(arr, 0, len);
out.flush();
bytesRead = len;
}
try {
System.out.println("wait ack");
socket.setSoTimeout(timeout);
String ack = (String) in.readObject();
System.out.println(ack);
if(bytesRead >= fileSize){
out.writeObject(Server.UPLOAD_COMPLETE_MSG);
System.out.println(Server.UPLOAD_COMPLETE_MSG);
break;
}else{
out.writeObject(Server.CHUNK_ACKNOWLEDGE_MSG);
}
}catch (SocketTimeoutException e){
out.writeObject(Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG);
System.out.println(Server.UPLOAD_ACKNOWLEDGE_RECEIVE_TIMEOUT_MSG);
break;
}finally {
socket.setSoTimeout(0);
}
}
}
}catch (IOException ioe){
ioe.printStackTrace();
}
}catch (FileNotFoundException fnfe){
System.out.println("No such file: " fileName);
}catch (Exception e){
e.printStackTrace();
}
finally {
try {
socket.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
我嘗試將byte陣列寫入客戶端的另一個檔案,并且副本是相同的。所以問題一定是在通過套接字發送資料期間。
Server.X_MSG 只是一個常量字串。我不知道是否混合readobject()并read(bytearray)在相同的ObjectInputStream原因,但任何問題。
uj5u.com熱心網友回復:
也許是因為fileOut.write(arr, 0, len);使用arr和len = in.read(bytes,0, chunkSize);使用bytes?它們不是同一個陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/368149.html
上一篇:從C中的雙向鏈接串列中洗掉特定項
