如何通过java套接字将目录中的多个文件从客户端传输到服务器?

时间:2014-02-13 15:38:03

标签: java sockets

我创建了一个简单的客户端 - 服务器java套接字应用程序,可以通过套接字将单个文件从客户端传输到服务器。我需要在我的应用程序中修改什么才能将目录中的多个文件发送到服务器? 这是我的简单客户:

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

}

这是我的简单服务器,它包含一个客户端处理程序和一个服务器.. 这是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();
        }
    }}

和服务器:

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

2 个答案:

答案 0 :(得分:0)

File directory = new File(directoryName);

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

因此,您获得了目录列表(目录中所有文件的列表),循环生成fList并逐个发送它们,就像使用单个文件一样:

for(File file : fList) {
//file sending stuff
}

答案 1 :(得分:-1)

如果要查看目录列表和文件列表,可以使用JFileChooser。例如:

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

选择文件:

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

         dstFile=jFilechooser1.getSelectedFile();

             }