0

I have created a simple client-server java socket app that can transfer a single file from client into the server through socket. What do I need to modify in my application so that I can send multiple files in a directory to the server? this my simple client:

public void connect() {
    while (!isConnected) {
        try {
            socket = new Socket("10.110.190.82", 7999);
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            isConnected = true;
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "Error. Server is not running\n '"+e.getMessage()+"' "+
                    "\nThis Client will now close.", "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    }
}

public void sendFile(String sourceFilePath, String fileName) {
    if(socket.isConnected()){
        while (socket.isConnected()) {
            fileEvent = new FileEvent_1();
            String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
            fileEvent.setDestinationDirectory(destinationPath);
            fileEvent.setFilename(fileName);
            fileEvent.setSourceDirectory(sourceFilePath);
            File file = new File(sourceFilePath);
            if (file.isFile()) {
                try {
                    DataInputStream diStream = new DataInputStream(new FileInputStream(file));
                    long len = (int) file.length();
                    byte[] fileBytes = new byte[(int) len];
                    int read = 0;
                    int numRead = 0;
                    while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
                            fileBytes.length - read)) >= 0) {
                        read = read + numRead;
                    }
                    fileEvent.setFileSize(len);
                    fileEvent.setFileData(fileBytes);
                    fileEvent.setStatus("Success");
                } catch (Exception e) {
                    e.printStackTrace();
                    fileEvent.setStatus("Error");
                }
            } else {
                System.out.println("path specified is not pointing to a file");
                fileEvent.setStatus("Error");
            }

            try {
                outputStream.writeObject(fileEvent);
                System.out.println("Done...Going to exit");
                JOptionPane.showMessageDialog(null, "Upload Success", "Success", JOptionPane.INFORMATION_MESSAGE);
                Thread.sleep(3000);
                System.exit(0);
            } catch (IOException e) {
                e.printStackTrace();
            } catch(InterruptedException ex){
                ex.printStackTrace();
            }
        }
    } else {
        JOptionPane.showMessageDialog(null, "Socket is not connected", "FAILED", JOptionPane.ERROR_MESSAGE);
    }

}

and this is my simple server, it contains a client handler and a server.. this is client_handler:

public class ClientHandler implements Runnable {
Socket socket;
PrintStream out;
private ObjectInputStream inputStream;
private FileEvent_1 fileEvent;
private File dstFile;
private FileOutputStream fileOutputStream;

ClientHandler(Socket s) {
        socket = s;
}

@Override
public void run() {
    try {
                out = new PrintStream(socket.getOutputStream());
                inputStream = new ObjectInputStream(socket.getInputStream());
                downloadFile();
    } catch (IOException e) {
                System.out.println("PrintStream Error");
    } 
    out.println("Hello!! I'm in!!!");

    try {
                socket.close();
    } catch (IOException e) {
                System.out.println("Failed to close, oddly...");
    }
}

    public void downloadFile() {
        try {
            fileEvent = (FileEvent_1) inputStream.readObject();
            if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
                System.out.println("Error occurred ..So exiting");
                System.exit(0);
            }
            String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
            if (!new File(fileEvent.getDestinationDirectory()).exists()) {
                new File(fileEvent.getDestinationDirectory()).mkdirs();
            }
            dstFile = new File(outputFile);
            fileOutputStream = new FileOutputStream(dstFile);
            fileOutputStream.write(fileEvent.getFileData());
            fileOutputStream.flush();
            fileOutputStream.close();
            System.out.println("Output file : " + outputFile + " is successfully saved ");
            Thread.sleep(000);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }}

and the server:

public static void main(String[] args) {
        try {
            socket = new ServerSocket(port);
            System.out.println("SERVER START");
            System.out.println("Bound to port: " + port);
        } catch (IOException e) {
            System.out.println("Cannot bind to port: " + port);
            System.exit(0);
        }
        while (true) {
            try {
                Socket s = socket.accept();
                System.out.println("New Client: "+s.getInetAddress().toString());
            (new Thread(new ClientHandler(s))).start();
            } catch (IOException e) {
                System.out.println("Failed to accept client");
            }
        }
}
Eugene
  • 4,829
  • 1
  • 24
  • 49
oka
  • 1
  • 3
  • Your DataInputStream isn't doing anything here. I wouldn't use ObjectOutputStream unless you are writing objects, and the main thing you are writing is the contents of a file. – Peter Lawrey Feb 13 '14 at 15:46

2 Answers2

0
File directory = new File(directoryName);

// get all the files from a directory
File[] fList = directory.listFiles();

So you get the directory listing (list of all files in the directory), loop through the resulting fList and send them one by one as you would with a single file:

for(File file : fList) {
//file sending stuff
}
Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
-1

You can use JFileChooser if you want see the list of directories and list of files. for example:

  JFileChooser jFilechooser1= new JFileChooser(new File("."));

to select the file:

   if (jFilechooser1.showOpenDialog(this)==JFileChooser.APPROVE_OPTION)
    {

         dstFile=jFilechooser1.getSelectedFile();

             }      
sam
  • 83
  • 1
  • 7