Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当我尝试使用套接字在计算机之间传输时,文件到达时为空_Java_Swing_Sockets - Fatal编程技术网

Java 当我尝试使用套接字在计算机之间传输时,文件到达时为空

Java 当我尝试使用套接字在计算机之间传输时,文件到达时为空,java,swing,sockets,Java,Swing,Sockets,嗨,我对Java比较陌生,对它的网络方面也很陌生,我真的需要一些帮助,请 在过去的几天里,我做了一些研究,因为几天前我对人际网络一无所知。有人问过类似的问题,但我似乎找不到答案来帮助我。同样,我对java网络非常陌生,因此不知道如何解决这个问题。请帮忙 我正在处理一个客户机/服务器关系的项目,我希望客户机能够通过套接字传输他们的个人音乐文件。每次我尝试这样做时,文件都会被创建,但它是空的。有网络经验的人能帮我吗 服务器代码: public class Server extends JFrame

嗨,我对Java比较陌生,对它的网络方面也很陌生,我真的需要一些帮助,请

在过去的几天里,我做了一些研究,因为几天前我对人际网络一无所知。有人问过类似的问题,但我似乎找不到答案来帮助我。同样,我对java网络非常陌生,因此不知道如何解决这个问题。请帮忙

我正在处理一个客户机/服务器关系的项目,我希望客户机能够通过套接字传输他们的个人音乐文件。每次我尝试这样做时,文件都会被创建,但它是空的。有网络经验的人能帮我吗

服务器代码:

 public class Server extends JFrame {


        //===============================
        // FIELDS
        //===============================

        // connection essentials
        private ServerSocket server;
        private Socket connection;
        private OutputStream outStream;
        private InputStream inStream;

        // file transfer essentials
        private FileInputStream fileInStream;
        private FileOutputStream fileOutStream;
        private BufferedInputStream bufInStream;
        private BufferedOutputStream bufOutStream;
        private int bytesRead;
        private int currentTot;

        // frame components
        private JTextArea textArea;
        private JButton ok;

        //===============================
        // CONSTRUCTORS
        //===============================

        public Server(){

            initComponents();

            try {
                runServer();
                getStreams();
                receiveFile();

            } catch (IOException ex) {

                System.out.print( "Error in constructor - Server" );
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            } // catch()
            finally{

                try {
                    close();

                } catch (IOException ex) {
                    System.out.println( "Error in finally - attempt to close" );
                    Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                } // catch()
            } // finally

        } // 0 Args  


        //===============================
        // CLASS METHODS
        //===============================

        private void runServer() throws IOException {

            *server = new ServerSocket( 7133, 100 );
            connection = server.accept(); // accept clients conn attempt
            textArea.setText( "Connection Established..." );
            //connection.setTcpNoDelay( true ); // stops nagles algorithm by 
            // halting buffering (waiting to receive confirmaion from client)

        } // runServer()

        private void getStreams() throws IOException{

            outStream = connection.getOutputStream();
            outStream.flush();

            inStream = connection.getInputStream();
            textArea.append( "\n\nReceiving files..." );

        } // getStreams()

        private void close() throws IOException{

            outStream.close();
            inStream.close();
            server.close();

        } // close()

        private void receiveFile() throws FileNotFoundException, IOException{

            byte byteArray[] = new byte[ 10000000 ];
            File receviedFile =  new File( "YES.mp3" );
            FileOutputStream FOS = new FileOutputStream( receviedFile );
            try (ByteArrayOutputStream BOS = new ByteArrayOutputStream()) {
                bytesRead = inStream.read(byteArray, 0, byteArray.length);
                currentTot = bytesRead;

                byteArray = BOS.toByteArray();

                do {
                    bytesRead = inStream.read(
                            byteArray, 0, (byteArray.length - currentTot));

                    if (bytesRead >= 0)
                        currentTot += bytesRead;

                    if(currentTot == byteArray.length )
                        textArea.append( "\n\nFile recieved" );



                } while (bytesRead > -1);

                BOS.write(byteArray, 0, currentTot);
                BOS.flush();
            }
            close();

        } // receiveFiles()

        private void initComponents() {

            // textArea
            textArea = new JTextArea();
            this.add( textArea, BorderLayout.CENTER );

            // send
            ok = new JButton( "OK" );
            this.add( ok, BorderLayout.SOUTH );

            addListeners();

            // frame fundamentals
            this.setVisible( true );
            this.setSize( 300, 150 );
            this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        } // initComponents()

        private void addListeners() {

            ok.addActionListener(
                new ActionListener(){
                    @Override
                    public void actionPerformed(ActionEvent e) {

                        textArea.setText( "File received and accepted" );

                    } // actionPerformed()
                }); // addActionListeners()

        } // addListeners()
        //===============================
        // SETTERS AND GETTERS
        //===============================

        public static void main(String[] args) {

            Server server = new Server();
        }

    } // class{}
客户端代码:

public class Client extends JFrame {


    //===============================
    // FIELDS
    //===============================

    // connection essentials
    private Socket connection;
    private InputStream inStream;
    private OutputStream outStream;

    // file transfer essentials
    private FileInputStream fileInStream;
    private FileOutputStream fileOutStream;
    private BufferedInputStream bufInStream;
    private BufferedOutputStream bufOutStream;

    // frame components
    private JTextArea textArea;
    private JButton choose;
    private JButton send;

    // file
    private File fileToSend;


    //===============================
    // CONSTRUCTORS
    //===============================

    public Client(){

        initComponents();

        try {
            getConnected();
            getStreams();

        } catch (IOException ex) {
            System.out.println( "Error in Client constructor" );
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);

        } finally{

        } // finally

    }    
    //===============================
    // CLASS METHODS
    //===============================

    private void getConnected() throws IOException {

        connection = new Socket( InetAddress.getLocalHost(), 7133 );
        textArea.setText( "Connection Established..." );

    } // getConnected()

    private void getStreams() throws IOException {

        outStream = connection.getOutputStream();
        outStream.flush();

        inStream = connection.getInputStream();

    } // getStreams()

    private void close() throws IOException{

        outStream.close();
        inStream.close();
        connection.close();

    } // close()

    private void sendFile( final File transfer ) 
            throws FileNotFoundException, IOException{

        byte fileInBytes[] = new byte[ (int) transfer.length() ];
        fileInStream = new FileInputStream( transfer );
        int start = 0;

        textArea.setText( "Sending files...." );
        while( (start = inStream.read()) > 0 )
            outStream.write( fileInBytes, 0, fileInBytes.length );

        bufInStream = new BufferedInputStream( fileInStream );

        outStream.flush();

        textArea.setText( "Transfer complete" );
        close();

    } // sendFile()

    private void initComponents() {

        // choose
        choose = new JButton( "CHOOSE" );
        this.add( choose, BorderLayout.NORTH );

        // textArea
        textArea = new JTextArea();
        this.add( textArea, BorderLayout.CENTER );

        // send
        send = new JButton( "SEND" );
        this.add( send, BorderLayout.SOUTH );

        addListeners();

        // frame fundamentals
        this.setVisible( true );
        this.setSize( 300, 150 );
        this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    } // initComponents()

    private void addListeners() {

        choose.addActionListener(
            new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent e) {

                    getFile();

                } // actionPerformed()
            }); // addActionListeners()

        send.addActionListener(
            new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent e) {
                    new Runnable(){

                        @Override
                        public void run() {

                            try {
                                sendFile(fileToSend);

                            } catch (IOException ex) {
                                System.out.println(
                                        "Error in send - actionPerformed");
                                Logger.getLogger(
                                        Client.class.getName()).log(
                                                Level.SEVERE, null, ex);

                            } // catch ()
                        } // run()
                    }; // runnable()

                } // actionPerformed()           
            }); // addActionListeners()

    } // addListeners()

   private void getFile()
   {
      JFileChooser fileChooser = new JFileChooser();
      fileChooser.setFileSelectionMode(
         JFileChooser.FILES_AND_DIRECTORIES );

      int result = fileChooser.showOpenDialog( this );

      // if user clicked Cancel button on dialog, return
      if ( result == JFileChooser.CANCEL_OPTION )
         System.exit( 1 );

      // getSelectedFile
      fileToSend = fileChooser.getSelectedFile();

      // display error if invalid
      if ( ( fileToSend == null ) || ( fileToSend.getName().equals( "" ) ) )
      {
         JOptionPane.showMessageDialog( this, "Invalid Name",
            "Invalid Name", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 );
      } // end if

   } // end method getFile


    //===============================
    // SETTERS AND GETTERS
    //===============================

    public static void main(String[] args) {

        Client client = new Client();
    }

} // class{}
在receiveFile()方法中,将接收到的内容的前10MB(可能全部)读入
byteArray
。然后,在以下行中:

byteArray = BOS.toByteArray();
您丢弃了先前的
byteArray
值,包括您收到的所有数据,并将其替换为
BOS
的空内容


相反,您需要做的是从输入流读取到缓冲区,然后从缓冲区写入FileOutputStream。无需为ByteArrayOutputStream费心。

谢谢您的快速回复,我非常感谢。你告诉我的很有道理,我现在要去尝试用代码实现它,可能需要一段时间,因为我对这个过程不是很有信心,但我会在我成功后发布我的结果。你在Swing API上犯了很多线程冲突。请看详细信息,谢谢你提供的信息。。我将查看并整理我的代码。。干杯