Skip to content Skip to sidebar Skip to footer

Read From Socket Until \r\n In Java

I want to implement a POP3 client. I know that in POP3 protocol, each message ends with \r\n. I want to write a recvuntil method in Java, which will be able to receive a whole mess

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:

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"