Skip to content
Advertisement

Android Socket BufferedReader readLine() not working when reading from the InputStream

I am trying to loop code inside a thread in order to check for new data form the server periodically. I am using InputStream.available() in order to check if there are any bytes to be read. If so, I open a new Thread and try to read the data using BufferedReader and then log it to the console.

In onCreate:

JavaScript

The two runnables:

JavaScript
JavaScript

The console:

JavaScript

The 5th line in the console represents the moment when I send some data from the server. I can see that the number of bytes in the InputStream modifies, then the BufferedReader consumes them, but the data isn’t logged to the console. The exception throws when I force close the server.

PS. I am new to threading and networking so I apologize if this is some rookie mistake I am making.

Thank you.

Advertisement

Answer

I have found the answer: The server wasn’t sending n or r at the end of the data and BufferedReader.readLine() looks for one of these characters. As a result, the InputStream was being read endlessly.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement