简体   繁体   English

如何通过套接字发送文件? 爪哇

[英]How can I send files through sockets? Java

I am trying to send a file through sockets, currently from client to server.我正在尝试通过套接字发送文件,目前是从客户端到服务器。 The file to be written is created, but when I open it, it's empty.要写入的文件已创建,但是当我打开它时,它是空的。 Also, If I send a string to the server after sending the file, what I send gets written onto the text file that was supposed to be received.此外,如果我在发送文件后向服务器发送一个字符串,我发送的内容将被写入应该接收的文本文件中。

I am testing with text files only.我仅使用文本文件进行测试。

Why does this happen?为什么会发生这种情况? How can I correct it?我该如何纠正?

jbutton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        JFileChooser fc = new JFileChooser();
                        fc.setCurrentDirectory(new File(System.getProperty("user.home")));
                        FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png","txt");
                        fc.addChoosableFileFilter(filter);
                        int result = fc.showSaveDialog(null);
                         if(result == JFileChooser.APPROVE_OPTION){
                             File selectedFile = fc.getSelectedFile();
                             String path = selectedFile.getAbsolutePath();
                            try {
                                userText.setText("Sending File: " + selectedFile);
                                file = new FileInputStream(path);
                                byte b[] = new byte[30000];
                                file.read(b,0,b.length);
                                os = connection.getOutputStream();
                                os.write(b,0,b.length);
                                
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            catch (IOException e) {
                                e.printStackTrace();
                            }
                            
                         }
                         else if(result == JFileChooser.CANCEL_OPTION){
                             System.out.println("No File Select");
                         }  
                    }
                    

//get stream to send and receive data 
    private void setupStreams() throws IOException{
        output = new ObjectOutputStream(socket.getOutputStream());
        output.flush();
        input = new ObjectInputStream(socket.getInputStream());
        showMessage("\n Streams Are now Set up \n");
    }
    
    //during the chat conversation
    private void whileChatting() throws IOException{
        String message = "You are now connected ";
        showMessage(message);
        ableToType(true);
        do {
            try {
                message = (String) input.readObject();
                showMessage("\n" + message);
                
                byte b[] = new byte[30000];
                InputStream is = socket.getInputStream();
                FileOutputStream fr = new FileOutputStream("C:\\Users\\Documents\\TestingFileClientToServer.txt");
                is.read(b,0,b.length);
                fr.write(b,0,b.length);
            
                
            }catch(ClassNotFoundException classNotFoundException) {
                showMessage("\n Error on input \n");
            }
            
        }while(!message.equals("CLIENT - END"));
    }

So this is wrong (in two places):所以这是错误的(在两个地方):

            fr.write(b,0,b.length);

You should get the number of bytes actually read in the read call and use that size in your write call.您应该获得在 read 调用中实际读取的字节数,并在 write 调用中使用该大小。

This is also a problem:这也是一个问题:

            message = (String) input.readObject();

don't use this unless you really are sending objects over streams... which you shouldn't除非你真的通过流发送对象,否则不要使用它......你不应该这样做

As to answering your question about why the file has no content: You need to close the socket on the sending side after all data has been sent and flushed.至于回答您关于文件为什么没有内容的问题:在发送并刷新所有数据后,您需要关闭发送端的套接字。 Then on the receiving side, you need to catch SocketException for Socket closure, then close the file you are writing to.然后在接收端,您需要为 Socket 关闭捕获 SocketException,然后关闭您正在写入的文件。 Not closing the file is why you are not seeing any content.不关闭文件是您看不到任何内容的原因。

Another thing is that you are creating Object streams for no reason.另一件事是您无缘无故地创建对象流。 Don't use Object streams and don't use Data streams.不要使用对象流,也不要使用数据流。 Just use raw Input/Output streams.只需使用原始输入/输出流。 You don't need buffers as you are doing efficient reading and writing.您不需要缓冲区,因为您正在进行高效的阅读和写作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM