卡在readLine()上,即使该行为空

时间:2018-12-07 19:36:05

标签: java loops sockets

我在服务器中编写了这个循环,他只是在其中向客户端发送一些字符串:

PrintWriter out = new PrintWriter(incoming.getOutputStream(), true);
for (int j = 0; j < i; j++) {
    out.println(tmp[j]); // send the strings to the client
}

客户端还有另一个循环来检索所有这些字符串,但从不退出。例如,如果我给他发送4个字符串,则输出为:
-hi
-如何
-是
-你
然后,在最后一个字符串之后,它挂起了,除了关闭服务器,我无法做其他任何事情。当我关闭它时,客户端从那一刻退出。这是无效的循环:

        /* PHASE 2: The client receives the ArrayList with the emails */
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line;
        String message[] = new String[5];
        for (int j=0; ((line = in.readLine()) != null) && (line.length())>0;) {
           System.out.println(line); //DEBUG
           message[j++] = line;
           if (j==5) {
                data = format.parse(message[3]);
                email.add(new Email((Integer.parseInt(message[0])), message[1], account, message[2], message[4], data));
                j=0;
            }
        }
        System.out.println("Out");

以下是带有循环的客户端代码:

public void loadData() throws IOException, ClassNotFoundException, ParseException {

    try {
        connect();
        ArrayList<Email> email = new ArrayList<Email>();
        DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        Date data;

        /* PHASE 1: The client sends a string to the server */
        try {
            PrintWriter out = new PrintWriter(s.getOutputStream(), true);
            out.println(account+"\n"); // send the account name to server

            /* PHASE 2: The client receives the ArrayList with the emails */
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String line;
            String message[] = new String[5];
            for (int j=0; ((line = in.readLine()) != null) && (line.length())>0;) {
                System.out.println(line); //DEBUG
                message[j++] = line;
                if (j==5) {
                    data = format.parse(message[3]);
                    email.add(new Email((Integer.parseInt(message[0])), message[1], account, message[2], message[4], data));
                    j=0;
                }
            }
            System.out.println("Out");

这是服务器代码:

class ThreadedEchoHandler implements Runnable {

    private Socket incoming;

    private String nomeAccount = "";

    public void run() {
        try {
            incoming = s.accept();
        } catch (IOException ex) {
            System.out.println("Unable to accept requests");
        }
        contenutoTextArea.append("Connected from: " + incoming.getLocalAddress() + "\n");
        textarea.setText(contenutoTextArea.toString());
        try {
            //PHASE 1: The server receives the email
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
                nomeAccount = in.readLine();
            } catch (IOException ex) {
                System.out.println("Not works");
            }

            //PHASE 2: I'm getting all the emails from the files
            File dir = new File("src/server/" + nomeAccount);
            String[] tmp = new String[100];
            int i = 0;
            for (File file : dir.listFiles()) {
                if (file.isFile() && !(file.getName().equals(".DS_Store"))) {
                    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                        String line;
                        while ((line = br.readLine()) != null) {
                            tmp[i++] = line;
                        }
                        br.close();
                    } catch (IOException ex) {
                        System.out.println("Cannot read from file");
                    }
                }
            }

            //PHASE 3: The server sends the ArrayList to the client
            PrintWriter out = new PrintWriter(incoming.getOutputStream(), true);
            for (int j = 0; j < i; j++) {
                out.println(tmp[j]); // send the strings to the client
            }

        } catch (IOException ex) {
            System.out.println("Cannot send the strings to the client");
        }

        //PHASE 4: Here I loop and wait for the client choise
        BufferedReader in;
        String op;
        boolean exit = false;
        try {
            in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
            while ((op = in.readLine()) != null) {
            System.out.println("OP: " + op);
            if (op.equals("Elimina")) {
                String tmp = in.readLine();
                contenutoTextArea.append("Ho eliminato la mail ").append(tmp).append(" \n");
                textarea.setText(contenutoTextArea.toString());
                File file = new File("src/server/" + nomeAccount + "/" + tmp + ".txt");
                file.delete();
            }
        }
            System.out.println("bbbbb");
        } catch (IOException ex) {
            System.out.println("Unable to read messages");
        } finally {
            try {
                incoming.close();
            } catch (IOException ex) {
                System.out.println("Cannot close the socket");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

基于读取您的客户端代码,它似乎在等待另一条消息,并且由于未到达流的末尾而未返回null。一旦终止服务器进程,该过程就会继续,这一事实证明了这一点。

如注释中所述,您应确保关闭服务器端的PrintWriter。但是,这本身不能解决问题,因为流在​​套接字上,并且只要套接字仍处于打开状态,就不会返回null。

您可以使用特定的控制字符串来回通信状态(永远不会被用户输入的东西,只是为了验证通信是否已完成),而不是检查是否为空,您可以d检查行是否与控制字符串匹配。只需在两侧使用该技术即可来回传递控制,并确保完成后关闭套接字。