2017-03-08 115 views
0

首先原谅我的编程说话我不是很善于解释的东西。Java套接字:如何在发送文件后保持套接字“打开”?

所以,我所做的是创建一个简单的聊天程序,它能够通过局域网进行通信。我最近做了它,所以我可以通过插座发送文件

这是一个框架,它有一个按钮,打开下面显示的文件选择器。

public void actionPerformed(ActionEvent arg0) { 
      JFileChooser chooser = new JFileChooser(); 
      FileNameExtensionFilter filter = new FileNameExtensionFilter(
       "Images", "jpg", "gif","png"); 
      FileNameExtensionFilter filter2 = new FileNameExtensionFilter(
        "Document", "docx", "doc","pdf","pptx"); 
      chooser.setFileFilter(filter); 
      chooser.setFileFilter(filter2); 
      Component parent = null; 
      int returnVal = chooser.showOpenDialog(parent); 
      if(returnVal == JFileChooser.APPROVE_OPTION) { 

       File filesend = new File(chooser.getSelectedFile().getPath()); 
       int count; 
       OutputStream out; 
       byte[] buffer = new byte[8192]; 
       try { 
        c.setMessage("fsendnow");// Sends a command to the server so it knows that im sending a file so it can prepare to receive it 
        c.msgOut(); 



        out = c.getMyClient().getOutputStream(); 
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(filesend)); 
        while ((count = in.read(buffer)) > 0) { 
         out.write(buffer, 0, count); 
         out.flush(); 
        } 

       }catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

而这不过是接收文件

}else if(line.equalsIgnoreCase("fsendnow")){ 

        byte[] buffer = new byte[8192]; 

        FileOutputStream fos = new FileOutputStream("a.png"); 
        BufferedOutputStream out2 = new BufferedOutputStream(fos); 

        int count; 
        InputStream in = client.getInputStream(); 
        while((count=in.read(buffer)) >=0){ 
         fos.write(buffer, 0, count); 
        } 
        fos.close(); 

        }else{ 
        cf.printMsg(client.getInetAddress().getHostAddress()+": "+line); 
       } 

问题IM衬片之后我发送一个文件,但它出现在文件夹中,代码,即时通讯无法打开它,因为它是“目前正在使用”。我的猜测是,正在运行的程序仍然在向它写入字节。由于这个套接字仍然“被使用”,我无法对程序做任何事情(发送消息/更多文件)。我尝试在这里关闭套接字,但是,我仍然需要它来发送消息,直到我退出聊天窗口。我该怎么办?我应该打开一个新的套接字连接吗?我真的不想这样做,我真的不想创建一个线程服务器。

    while ((count = in.read(buffer)) > 0) { 
         out.write(buffer, 0, count); 
         out.flush(); 
        } 
        //c.getMyClient().close(); CLOSES THE SOCKET 
       }catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

所以我如何告诉java即时通讯发送文件并停止从“阅读”图像。对不起,如果它是一个noob问题。

+0

你最后关闭文件吗? –

+0

我不知道,但我认为读(缓冲区)调用将阻止线程和输出流文件将永远不会关闭。 –

+0

为了解决这个问题,我认为首先你需要接收字节文件的总数并且在读取迭代时增加,并且如果字节数达到文件中的字节总数则打破循环。 –

回答

0

这可能是因为您希望从套接字读取8192个字节,并且您正尝试在该文件中写入8192个字节,但它可能会从套接字中收回少于8192个字节,并且可能会阻止该文件,直到8192个字节已经写入文件

另外,我建议先读8192个字节,当你拥有人缓冲区写它,因为你总是从偏移0书面方式:

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