2017-10-18 111 views
-1

我使用bellow代碼發送文件文件master到客戶端,但是當我使用mulltiple時間這段代碼針對不同的文件程序給出了「SOCKET CLOSED」錯誤,因爲我使用「out.close );「和」in.close();「我無法解決這些問題你有什麼建議。此外,我儘量不關閉套接字但沒有奏效下一個文件是不是發送此時在同一個套接字中多次發送文件

private void SendFiletoClient(Socket Socket, String fileName) { 
     try { 
      File file = new File(MasterPath + "/" + fileName);// Get the size of the file 
      long length = file.length(); 
      byte[] bytes = new byte[16 * 1024]; 
      InputStream in = new FileInputStream(file); 
      OutputStream out = Socket.getOutputStream(); 

      int count; 
      while ((count = in.read(bytes)) > 0) { 
       out.write(bytes, 0, count); 
      } 

      out.close(); 
      in.close(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

/////

private void addFileToClient(Socket Socket, String fileName) { 

     File file = new File(MasterPath + fileName); 
     try { 
      file.createNewFile(); 

      InputStream in = Socket.getInputStream(); 
      OutputStream out = new FileOutputStream(MasterPath + fileName); 

      byte[] bytes = new byte[16 * 1024]; 
      int count; 
      while ((count = in.read(bytes)) > 0) { 
       out.write(bytes, 0, count); 
      } 
      out.close(); 
      in.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
+0

請勿關閉插座? – John3136

+0

這是行不通的,我嘗試了很多時間 – stigmata2

+0

'file.createNewFile();'在這裏沒有意義。您迫使文件系統(a)刪除任何現有文件,(b)創建一個新文件,然後(c)在執行新的FileOutputStream()時再執行所有操作。這完全浪費了時間和空間。 – EJP

回答

0

它,因爲你是關閉套接字

out.close(); 
    in.close(); 

要麼關閉套接字並保持連接活着,要麼每次你想通過它發送東西時打開關閉。

在你的情況下,關閉輸出(文件)並保持活動輸入(套接字)。問題在於,另一方發生了什麼?