I have written the code for sending/receiving data from a client socket. The sending data step has been done successfully, but when I want to read the data from a socket, the readLine() method block program while there isn’t data to be read.
This is my code:
StringBuffer document = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
document.append(line + "\n");
reader.close()
thanks all
I can read all received data, but readLine or read(byte[], int, int) methods block program when there is no data to read, while this method must return null/-1 in this time.
That’s because the
readLine()function is a blocking call, so of course it’s going to block.To be more constructive, calls to methods like
readLine()should be in a separate thread so that the blocking call does not affect the rest of your code. From the class which is reading, I would recommend creating a thread purely to control reading from the socket.I would pass a reference to the creating class so that if the thread receives information, the parent class can use it.