0

хочу передать от сервера к клиенту текстовый файл при получении вывести его на консоль клиента. Использую class File - не получается. Вот исходники:

public class VServerThreads {
    private static ServerSocket serverSocket = null;

    public static void main(String[] args) {
        try {
            try {
                serverSocket = new ServerSocket(2222);
                System.out.println("Initialized");
//            waiting for a client
                while (true) {
                    Socket socket = serverSocket.accept();
                    System.out.println(socket.getInetAddress().getHostAddress() + " connected");
//                creating a new thread for a new client
                    VServer vServer = new VServer(socket);
                    new Thread(vServer).start();
                }
            }finally {
                if(!serverSocket.isClosed()) {
                    serverSocket.close();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}



class VServer implements Runnable {
    private Socket clientSocket;
    private static AtomicInteger userNumIncrement;
    private int userNum = 0;

    private static List<Document> documentsList;
    private static List<File> filesList;

    static {
        userNumIncrement = new AtomicInteger(0);
    }

    public VServer(Socket socket) throws IOException {
        userNum = userNumIncrement.incrementAndGet();
        clientSocket = socket;
        documentsList = new ArrayList<>();
        filesList = new ArrayList<>();

        documentsList.add(new Document(75, "Ulysses", 13.20));
        documentsList.add(new Document(75, "Moby Dick", 15.70));
        documentsList.add(new Document(110, "Hamlet", 18.10));
        documentsList.add(new Document(110, "The Odyssey", 18.30));
        documentsList.add(new Document(130, "Great Gatsby", 20.10));
        documentsList.add(new Document(130, "Divine Comedy", 21.15));
        documentsList.add(new Document(200, "Madame Bovary", 25.10));
        documentsList.add(new Document(200, "The Iliad", 27.40));
        documentsList.add(new Document(500, "Lolita", 30.50));
        documentsList.add(new Document(500, "Alice", 32.60));

        filesList.add(new File("/src/aas/documents/Ulysses.txt"));
        filesList.add(new File("/src/aas/documents/MobyDick.txt"));
        filesList.add(new File("/src/aas/documents/Hamlet.txt"));
        filesList.add(new File("/src/aas/documents/Oddysey.txt"));
        filesList.add(new File("/src/aas/documents/GreatGatsby.txt"));
        filesList.add(new File("/src/aas/documents/DivineComedy.txt"));
        filesList.add(new File("/src/aas/documents/MadameBovary.txt"));
        filesList.add(new File("/src/aas/documents/Iliad.txt"));
        filesList.add(new File("/src/aas/documents/Lolita.txt"));
        filesList.add(new File("/src/aas/documents/Alica.txt"));
    }


    @Override
    public void run() {
            try(Socket clientSocket = this.clientSocket;
                DataInputStream in = new DataInputStream(clientSocket.getInputStream());
                DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
                ObjectOutputStream objOut = new ObjectOutputStream(clientSocket.getOutputStream()))
            {
                String line;
                while (true) {
                    line = in.readUTF();
                    if(line.equals("retrieveDocuments")) {
                        objOut.writeObject(documentsList);
                        objOut.flush();
                    }
                    else if(line.equals("buyDocument№")) {
                        int docNum = in.readInt();
                        if(docNum < 1 || docNum > documentsList.size()) {
                            System.out.println("You have entered a wrong document number");
                            continue;
                        }
                        if (in.readUTF().equals("Validation")) {
                            objOut.writeObject(filesList.get(docNum - 1));
                            objOut.flush();
                        }
                        else {
                            System.out.println("There is not enough money");
                            continue;
                        }
                    }
                    else if (line.equals("amIAdmin?")) {
                    }
                    else if (line.startsWith("/quit")) {
                        break;
                    }

                }

                out.writeUTF("*** Bye " + " ***");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                disconnect();
        }
    }

    public void disconnect() {
        try {
            System.out.println("Disconnected");
            clientSocket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {

        }
    }


}

public class VClient {
    private static Socket socket = null;
    private static DataInputStream in = null;
    private static DataOutputStream out = null;
    private static Scanner keyboard = null;
    private static ObjectInputStream objIn = null;
    private static List<Document> documentsList;
    private static double account;

    public static void main(String[] args) {
        String address = "127.0.0.1";
        account = 100.00;
        boolean isListInitialized = false;
        try {
            InetAddress ipAddress = InetAddress.getByName(address);
            socket = new Socket(ipAddress, 2222);
            try {
                keyboard = new Scanner(System.in);
                in = new DataInputStream(socket.getInputStream());
                out = new DataOutputStream(socket.getOutputStream());
                objIn = new ObjectInputStream(socket.getInputStream());

                String line;
                while (true) {
                    showMenu();
                    line = keyboard.nextLine();
                    if (isDigit(line)) {
                        int choice = Integer.parseInt(line);
                        if (choice == 1) {
                            out.writeUTF("retrieveDocuments");
                            out.flush();
                            documentsList = (ArrayList<Document>) objIn.readObject();
                            int i = 1;
                            for (Document document : documentsList) {
                                System.out.println(i++ + ": " +  document);
                            }
                            isListInitialized = true;
                        } else if (choice == 2) {
                            if(!isListInitialized) {
                                System.out.println("For the first watch a documents List - choice №1");
                                continue;
                            }
                            System.out.println("Enter the number of document you want to buy");
                            line = keyboard.nextLine();
                            if (isDigit(line)) {
                                if(Integer.valueOf(line) < 1 || Integer.valueOf(line) > documentsList.size()) {
                                    System.out.println("Wrong document index");
                                    continue;
                                }
                                out.writeInt(Integer.valueOf(line));
                                out.flush();
                                account -= documentsList.get(Integer.valueOf(line)).getDocumentPrice();
                                out.writeUTF("Validation");
                                out.flush();
                                File file = (File) objIn.readObject();
                                System.out.println(file);

                            } else {
                                System.out.println("It is a wrong input");
                                continue;
                            }
                        } else if (choice == 3) {
                            out.writeUTF("amIAdmin?");
                            out.flush();
                        } else if (choice == 4) {
                            out.writeUTF("/quit");
                            out.flush();
                            line = in.readUTF();
                            if (line.contains("*** Bye"))
                                break;
                        } else {
                            System.out.println("Wrong input. Please re-enter");
                            continue;
                        }
                    } else {
                        System.out.println("Wrong input. Please re-enter");
                        continue;
                    }


                }
            } finally {
                in.close();
                out.close();
                socket.close();
                objIn.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    private static void showMenu() {
        System.out.println("Enter a number of the menu");
        System.out.println("1: If you want to get document names and costs press 1");
        System.out.println("2: If you want to read the entire contents of the given file press 2");
        System.out.println("3: If you are an admin press 3");
        System.out.println("4: Quit");
    }
    private static boolean isDigit(String s) throws NumberFormatException {
        try {
            Integer.parseInt(s);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }


}

1 ответ 1

2

DataOutputStream тут не годится. Объекты типа File не содержат никаких данных из файла. Это всего лишь указатель на файл или директорию в файловой системе.

Вам же нужно придумать как передавать имя файла, а потом его содержимое.

Альтернативный вариант - передавать файлы, предварительно помещая их в zip архив и распаковывая на клиенте.

Похожий вопрос уже разбирали тут: JAVA, передача папки через socket.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.