Read From Socket Until \r\n In Java
Solution 1:
The Python code reads one octet at a time, immediately appends it to answer
and signals it's done if at the current iteration answer
ends with CRLF
.
The Java code hangs because BufferedReader.readLine()
returns the line content after stripping the line termination. At this point answer
does not contain CRLF
, so readLine()
is called once again, and since the stream is not closed from the other end (your program would then throw a NullPointerException
) and you have an infinite read timeout (you would see a SocketTimeoutException
), it hangs, forever waiting for the next line.
The correct version is
Socketsocket= connect(); // Implement thisScannerscanner=newScanner(newInputStreamReader(socket.getInputStream(), "ASCII"));
scanner.useDelimiter("\r\n");
Stringresponse= scanner.nextLine();
socket.close();
Notes:
- always set a timeout on sockets.
- you may want to account for multiline messages.
Solution 2:
you can use the Scanner class (it accepts an InputStream
as a constructor param ) and set the delimiter using useDelimiter
method. to read messages that end with \r\n
Post a Comment for "Read From Socket Until \r\n In Java"