BufferedReader readLine() blocks

前端 未结 7 2135
轻奢々
轻奢々 2020-12-06 02:02

When receiving data using readLine(), even though I put a \"\\n\" at the end of the message using the .flush when sending the message, the while loop that reads my message s

7条回答
  •  再見小時候
    2020-12-06 02:39

    It'd be better avoid using readline(). This method is dangerous for network communications because some servers don't return LF/CR symbols and your code will be stuck. When you read from a file it isn't critical because you will reach end of the file anyway and stream will be closed.

    public String readResponse(InputStream inStreamFromServer, int timeout) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inStreamFromServer, Charsets.UTF_8));
        char[] buffer = new char[8092];
        boolean timeoutNotExceeded;
        StringBuilder result = new StringBuilder();
        final long startTime = System.nanoTime();
        while ((timeoutNotExceeded = (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime) < timeout))) {
            if (reader.ready()) {
                int charsRead = reader.read(buffer);
                if (charsRead == -1) {
                    break;
                }
                result.append(buffer, 0, charsRead);
            } else {
                try {
                    Thread.sleep(timeout / 200);
                } catch (InterruptedException ex) {
                    LOG.error("InterruptedException ex=", ex);
                }
            }
        }
        if (!timeoutNotExceeded) throw new SocketTimeoutException("Command timeout limit was exceeded: " + timeout);
    
        return result.toString();
    }
    

    It has a timeout and you can interrupt communication if it take a lot of time

提交回复
热议问题