Fedor Finkenflugel
Fedor Finkenflugel

Reputation: 355

BufferedReader.lines().foreach() never terminates

I'm trying to read a HTTP request from a Bufferedreader, that gets Socket.getInputStream() as input. However, when I use Bufferedreader.lines().foreach(), it never terminates and it just gets stuck.

My code (simplified):

Socket socket = new ServerSocket(9090);
Socket newConnection = socket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(newConnection.getInputStream()));
reader.lines().forEach(s -> System.out.println(s));

Upvotes: 0

Views: 1553

Answers (2)

user207421
user207421

Reputation: 310980

You need to read more about the HTTP 1.1 protocol. Requests aren't terminated by end of stream. They are terminated by exhausting the byte count in the Content-length header, or of the cumulative chunks if chunked transfer mode is in use. If they were exhausted by end of stream, you could never send a response.

Upvotes: 4

Kojotak
Kojotak

Reputation: 2070

Try creating your socket with parameter-less constructor and use connect() method with port and timeout parameter. This will prevent endless freeze.

Upvotes: -2

Related Questions