Java8 BufferedReader.lines() stream 比命令式解决方案挂程序

Java8 BufferedReader.lines() stream hangs program compared to imperative solution

我目前正在用 ServerSocket 编写一个基本的网络服务器,我正在尝试使用 java 8 个流来清理我的代码。这一直很顺利,但是当我尝试使用 BufferedReader 使用流读取请求时,我的程序挂起并且请求从未被完全读入。我在下面列出了不同之处。

使用流:

InputStream stream = socket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
System.out.println("----------REQUEST START---------");
List<String> rawRequest = in.lines()
    .peek(System.out::println)
    .map(line -> line.toString())
    .collect(Collectors.toList());
System.out.println("----------REQUEST END---------\n\n");

没有流:

 InputStream stream = socket.getInputStream();
 BufferedReader in = new BufferedReader(new InputStreamReader(stream));
 List<String> rawRequest = new ArrayList<>();
    try {

      System.out.println("----------REQUEST START---------");
      // read only headers
      for (String line = in.readLine(); line != null && line.trim().length() > 0; line = in.readLine()) {
        System.out.println(line);
        rawRequest.add(line);
      }
      System.out.println("----------REQUEST END---------\n\n");
    } catch (IOException e) {
      System.out.println("Error reading");
      System.exit(1);
    }

据我所知,除了错误处理之外,这些应该大致相同,只是在流片段中 System.out.println("----------REQUEST END---------\n\n"); 永远不会 运行。

他们不是'roughly equivalent'。您的 'imperative solution' 在读取空行时终止。另一个仅在流结束时终止,不会到达,因为对等方保持连接打开以便接收您的回复。

你应该像这样检查空行和空白行

in.lines()
.map(line -> line.trim())
.filter(line -> !line.isEmpty())
.map(line -> line.toString())
.collect(Collectors.toList());

这将跳过空行