[Solved] Buffered Socket Reader doesn’t wait for data from remote connection


You shouldn’t be using ndataServerReader.ready(). Your do/while loop (which should almost certainly just be a while loop) appears to assume that ndataServerReader.ready() indicates there’s more data to be read, which is not what it’s for.

The Javadoc for Reader describes the ready() method as:

Tells whether this stream is ready to be read.

Returns: True if the next read() is guaranteed not to block for input, false
otherwise. Note that returning false does not guarantee that the next
read will block.

In other worse, Reader.ready() will return false if the reader will wait for more data before returning if you attempt to read from it. This does not mean the Reader is done, and in fact you should expect this method to return false often when working with a network stream, as it could easily have delays.

Your code currently is likely reading one line (in the do block) then checking if the reader is ready (in the while), which it probably isn’t, and then exiting successfully. No exceptions are being thrown – you’d see a SEVERE level logging message if they were.

Instead of using ready(), take advantage of the documented behavior of readLine() that says it returns:

A String containing the contents of the line, not including any
line-termination characters, or null if the end of the stream has been
reached

In other words, simply doing:

String ndata = reader.readLine();
while (ndata != null) {
    osw.write(ndata+"\n");
    osw.flush();
    LOG.log(Level.INFO,"Sent");

    ndata reader.readLine();
}

Is sufficient to read the whole input stream.

Reference reading: What’s the difference between (reader.ready()) and using a for loop to read through a file?

2

solved Buffered Socket Reader doesn’t wait for data from remote connection