简体   繁体   中英

Read data from a client socket in Java

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.

BufferedReader has a method called 'ready()' which returns true when data is ready to be received. If you don't want to be blocked at 'readLine()' call, check first if data is ready to be read.

Have a look at the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM