【问题标题】:How can I send files through sockets? Java如何通过套接字发送文件?爪哇
【发布时间】:2020-11-16 23:05:24
【问题描述】:

我正在尝试通过当前从客户端到服务器的套接字发送文件。要写入的文件已创建,但当我打开它时,它是空的。另外,如果我在发送文件后向服务器发送一个字符串,我发送的内容会被写入应该接收的文本文件中。

我只测试文本文件。

为什么会这样?我该如何纠正?

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"));
    }

【问题讨论】:

  • 仅供参考,除非您想要与之通信的另一端已经设置了一个,否则真的没有充分的理由再使用原始套接字了。如果您要设置连接的两端,WebSockets/WebSocket API 确实是一个更好的选择。

标签: java file client-server serversocket


【解决方案1】:

所以这是错误的(在两个地方):

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

您应该在 read 调用中获取实际读取的字节数,并在 write 调用中使用该大小。

这也是个问题:

            message = (String) input.readObject();

除非你真的通过流发送对象,否则不要使用它......你不应该这样做

关于回答为什么文件没有内容的问题:您需要在发送并刷新所有数据后关闭发送端的套接字。然后在接收端,您需要为 Socket 关闭捕获 SocketException,然后关闭您正在写入的文件。不关闭文件是您看不到任何内容的原因。

另一件事是您无缘无故地创建对象流。不要使用对象流,也不要使用数据流。只需使用原始输入/输出流。您不需要缓冲区,因为您正在执行高效的读写操作。

【讨论】:

  • 在做文件IO的时候一般不会有问题,但是你漏掉了没有放入循环的单个read
  • @MaartenBodewes Egad 你的意思是我错过了 readObject 电话吗?总的! (忽略我的戏剧)我已经更新了我的答案:)
  • 不,我的意思是file.read(b,0,b.length);,但是是的,还有一个。
  • @ControlAltDel 感谢您的澄清!!!我会努力的。
  • @ArianisRodriguez 我现在看到了,正如你所说,它应该在循环中
猜你喜欢
  • 2015-01-26
  • 1970-01-01
  • 2013-09-27
  • 2011-02-24
  • 2012-07-12
  • 2015-08-28
  • 2021-07-06
相关资源
最近更新 更多