2013-01-31 251 views
0

我在通過套接字發送文件(不一定是txt文件)時遇到問題。我有2個類:服務器,客戶端。當我從套接字輸出流中讀取數據並希望寫在一個文件中的字節,它看起來工作,但是當我打開文件它什麼都沒有(損壞顯示大小= 0 kb)。我也希望它通過套接字傳輸所有類型的文件。我不想使用appache commons net。 這裏是我的代碼 服務器類在ftp協議中通過套接字傳輸文件

FileOutputStream toFile1 = new FileOutputStream(f);    
BufferedOutputStream toFile= new BufferedOutputStream(toFile1); 
BufferedInputStream bis=new BufferedInputStream(incoming.getInputStream()); 
byte[]buffer=new byte[2048]; 
int bytesRead=0; 



while((bytesRead = bis.read(buffer)) >= 0) 
{ 
    toFile.write(buffer, 0, bytesRead); 

} 

toFile.close(); 
toFile1.close(); 
bis.close(); 
out.println("226 Connection Closed"); 
out.flush(); 
        }     

Client類

BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream()); 
byte[] buffer = new byte[60*2024]; 
int bytesRead = 0; 
while ((bytesRead = input.read(buffer,0,60*1024)) != -1) { 
     output.write(buffer, 0, bytesRead); 
} 

回答

0

,可以與該代碼發生的唯一方法是,如果你要發送一個零長度的文件,也可能從一個文件輸入讀取已經定位在EOF處的流,否則之後會查看錯誤的文件。

+0

謝謝all.I必須刷新並關閉我的客戶端的輸出。我還有一個問題:如果在工作中,客戶端變得不耐煩,服務器應該做什麼? – Proud

+0

@Proud關閉數據連接,中止操作,並通過命令連接報告錯誤。也許刪除部分上傳,取決於您的要求。如果寫入命令通道的異常寫入,請關閉該命令。 – EJP