2017-10-18 100 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(); 

要么关闭套接字并保持连接活着,要么每次你想通过它发送东西时打开关闭。

在你的情况下,关闭输出(文件)并保持活动输入(套接字)。问题在于,另一方发生了什么?