使用Java中的套接字在客户端和服务器之间传输文件

时间:2016-12-08 14:50:30

标签: java sockets client-server

我正在尝试使用套接字在java中构建客户端服务器模型来共享文件。

它适用于一次循环迭代以发送文件,但之后在服务器上没有收到任何数据。请看一下我的代码并建议我纠正这个问题。

FileClient.java

public class FileClient {

private void listFiles() {
    try {
        DataInputStream dis = new DataInputStream(s.getInputStream());
        while (dis.available() > 0) {
            System.out.println(dis.readUTF());
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

private static void selectAndDownloadFiles() {

}

private Socket s;
public FileClient(String host, int port) {
    try {
        s = new Socket(host, port);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void sendFile(String file) throws IOException {
    DataOutputStream dos = new DataOutputStream(s.getOutputStream());
    FileInputStream fis = new FileInputStream(file);
    File myFile = new File (file);

    dos.writeUTF(file);
    dos.writeInt((int)myFile.length());
    try {
        sleep(2);
    } catch (InterruptedException ex) {
        Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    byte[] buffer = new byte[8192];

    while (fis.read(buffer) > 0) {
        dos.write(buffer);
    }


}

public static void main(String[] args) {
    int choice = 0;
    Scanner in = new Scanner(System.in);
    FileClient fc = new FileClient("localhost", 1988);

    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(fc.s.getOutputStream());
    } catch (IOException ex) {
        Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    do {
        try {
            System.out.println("Choose an action to perform..!");
            System.out.println("1. List the files..");
            System.out.println("2. Select and download files");
            System.out.println("3. Send a file..");
            System.out.println("0. Exit..");

            choice = in.nextInt();
            String fileName;
            switch (choice) {
                case 1:

                    try {

                        dos.write(choice);
                        System.out.println("List Files Request Sent..!");
                    } catch (IOException ex) {
                        Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    sleep(2);
                    fc.listFiles();
                    break;
                case 2:
                    selectAndDownloadFiles();
                    break;
                case 3:
                    try {
                        dos.write(choice);
                    } catch (IOException ex) {
                        Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    System.out.println("Enter file name to send");
                    fileName = in.next();

                    try {
                        fc.sendFile(fileName);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }

                    break;
                case 0:
                    System.exit(0);
                    break;
                default:
                    System.out.println();

            }
        } catch (InterruptedException ex) {
            Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    } while (choice != 0);

}

}

FileServer.java

public class FileServer extends Thread {

private static ServerSocket ss;

public FileServer(int port) {
    try {
        ss = new ServerSocket(port);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void run() {
    File theDir = new File("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles");

// if the directory does not exist, create it
    if (!theDir.exists()) {

        boolean result = false;

        try {
            theDir.mkdir();
            result = true;
        } catch (SecurityException se) {
            //handle it
        }
        if (result) {
            System.out.println("DIR created");
        }
    }

    while (true) {
        try {
            Socket clientSock = ss.accept();
            DataInputStream dis = new DataInputStream(clientSock.getInputStream());
            DataOutputStream dos = new DataOutputStream(clientSock.getOutputStream());
            int choice;
            while ((choice = dis.read()) > 0) {

                switch (choice) {
                    case 1:
                        System.out.println("List Files Request Received..!");
                        listFiles(clientSock);
                        System.out.println("List Files Response Sent..!");
                        break;
                    case 2:
                        sendSelectedFiles();
                        break;
                    case 3:
                        saveFile(clientSock);

                        break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

private void saveFile(Socket clientSock) throws IOException {
    DataInputStream dis = new DataInputStream(clientSock.getInputStream());
    String fileName = dis.readUTF();
    int filesize = dis.readInt();
    FileOutputStream fos = new FileOutputStream("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles\\" + fileName);
    try {
        sleep(2);
    } catch (InterruptedException ex) {
        Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    byte[] buffer = new byte[8192];

     // Send file size in separate msg
    int read = 0;
    int totalRead = 0;
    int remaining = filesize;
    while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
        totalRead += read;
        remaining -= read;
        System.out.println("read " + totalRead + " bytes.");
        fos.write(buffer, 0, read);
    }

    //fos.close();
    //dis.close();
}

public static void main(String[] args) {
    FileServer fs = new FileServer(1988);
    fs.start();
}

private void listFiles(Socket clientSock) {

    File folder = new File("C:\\Users\\Mehroz Irshad\\Desktop\\ServerFiles");
    File[] listOfFiles = folder.listFiles();
    try {
        DataOutputStream dos = new DataOutputStream(clientSock.getOutputStream());
        if (listOfFiles.length > 0) {
            for (int i = 0; i < listOfFiles.length; i++) {
                dos.writeUTF(listOfFiles[i].getName());
            }

        } else {
            dos.writeUTF("There are no files on the server..!");
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

private void sendSelectedFiles() {
}

}

附有输出图像。

Client Output

enter image description here

0 个答案:

没有答案