Results 1 to 8 of 8
  1. #1
    Join Date
    Dec 2013
    Location
    Dublin
    Posts
    32
    Rep Power
    0

    Default File is arriving empty when I attempt to transfer between computers using sockets

    Hi I relatively new to Java and very new to the networking side of it and I really need some help please..?

    I am working on a project with client/server relationship and I want the client to be able to transfer their personal music files over the socket. Every time I attempt to do it the file is created but it is empty. Could someone with networking experience help me please?

    Server code:

    Java Code:
    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{}
    Client code:

    Java Code:
    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 );
            
    //        bufInStream.read( fileInBytes, 0, fileInBytes.length );
    //        outStream.write( fileInBytes, 0, fileInBytes.length );
            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()
       {
          // display file dialog, so user can choose file or directory to open
          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{}

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,755
    Rep Power
    25

    Default Re: File is arriving empty when I attempt to transfer between computers using sockets

    Where is the code that writes to the file?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Join Date
    Dec 2013
    Location
    Dublin
    Posts
    32
    Rep Power
    0

    Default Re: File is arriving empty when I attempt to transfer between computers using sockets

    It is in the receiveFile() method of the server class. Or it is suppose to be anyway.. That is what I also find confusing, converting bytes to files and vice versa.
    I have read up on the subject over the net and seen some good posts, but cannot really get my head around how to connect the file to the byteArray[] ???

    Thanks for the swift response...

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,755
    Rep Power
    25

    Default Re: File is arriving empty when I attempt to transfer between computers using sockets

    it is suppose to be
    Before trying to fix this code, make a small test program that writes some bytes to a file. You need to experiment with using classes and methods for writing bytes to a file to learn what to do.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    Join Date
    Dec 2013
    Location
    Dublin
    Posts
    32
    Rep Power
    0

    Default Re: File is arriving empty when I attempt to transfer between computers using sockets

    Ok Thanks good advice.. I will try that now and post how I get on..

  6. #6
    Join Date
    Dec 2013
    Location
    Dublin
    Posts
    32
    Rep Power
    0

    Default Re: File is arriving empty when I attempt to transfer between computers using sockets

    I have been reading up on how to 'read and write' to files and I have been practicing writing short classes to help understand how to go about it in Java...
    I have this class that takes an mp3 file from my library and creates a new mp3 file. It is working perfectly. But I am a little stumped still as to how to implement it using sockets over a network. Have you anymore advice you could share with me please..?

    Here is my code:

    Java Code:
    public class SimpleFile {
        
        //===============================
        // FIELDS
        //===============================
        
        //===============================
        // CONSTRUCTORS
        //===============================
        
        //===============================
        // CLASS METHODS
        //===============================
        
        public void readStream(){
            
            try( FileInputStream file = new FileInputStream( 
                    "C:\\Users\\Eric\\Documents\\NetBeansProjects\\Arqhive.3"
                            + "\\src\\Music\\Pharrell Williams - Happy.mp3" );
                 BufferedInputStream buff = new BufferedInputStream( file );   ){
                
                int in;
                int count = 0;
                byte array[] = new byte[ file.available() ];
                
                for( int current = 0; 
                         current < array.length; 
                         current++){
                    
                    array[ current ] = (byte) buff.read();
                }
                
                writeStream( array );
                
            } catch (FileNotFoundException ex) {
                Logger.getLogger(SimpleFile.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ioe) {
                Logger.getLogger(SimpleFile.class.getName()).log(Level.SEVERE, null, ioe);
            }
                
            
        }
        
        public void writeStream( byte[] byteArray ){
         
            try( FileOutputStream file = new FileOutputStream( "YES.mp3" );
                 BufferedOutputStream buff = new BufferedOutputStream( file );   ){
                
                buff.write(byteArray);
                
            } catch (FileNotFoundException ex) {
                Logger.getLogger(SimpleFile.class.getName()).log(Level.SEVERE, null, ex); 
            } catch (IOException ioe) {
                Logger.getLogger(SimpleFile.class.getName()).log(Level.SEVERE, null, ioe); 
            }
        } // write()    
            
        //===============================
        // SETTERS AND GETTERS
        //===============================
        
        public static void main(String[] args) {
            
            SimpleFile y = new SimpleFile();
            y.readStream();
        }
        
    } // class{}
    Last edited by Castro__711; 05-28-2014 at 10:03 PM. Reason: Code was displayed as normal text + I am a little stump

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,755
    Rep Power
    25

    Default Re: File is arriving empty when I attempt to transfer between computers using sockets

    using sockets
    The Socket class has a method that returns an input stream that you can read from to get the bytes sent over the network.

    NOTE: The bytes available make not be all the bytes that are being sent. Various events can cause the bytes being sent to be split up and for the split to arrive at different times.
    Last edited by Norm; 05-28-2014 at 10:26 PM.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,169
    Rep Power
    20

    Default Re: File is arriving empty when I attempt to transfer between computers using sockets

    Your test method(s) for moving a file are going to consume more memory than needed.
    You are reading the entire file into memory before writing it out.

    The usual technique (and the one you seem to have been trying to use in your original code) is to read a chunk off the input stream into a byte[], then write the populated bits of that array (as defined by the byte count returned by the read method) to the output stream.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. File Transfer with Sockets
    By bockymurphy in forum New To Java
    Replies: 6
    Last Post: 12-10-2011, 01:23 AM
  2. Replies: 0
    Last Post: 04-08-2011, 10:46 AM
  3. Copying a file (.docx) from computers
    By chyrl in forum Networking
    Replies: 3
    Last Post: 07-02-2010, 03:02 PM
  4. Sockets for computers in wireless network
    By etrynus in forum Networking
    Replies: 2
    Last Post: 12-03-2008, 12:39 AM
  5. File and Message transfer over sockets!
    By rameshraj in forum Networking
    Replies: 3
    Last Post: 05-14-2008, 09:13 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •