Recently, when the classmate did the experiment, when the server side returned, using the BufferedReader class of ReadLine, he wrote, while (Reader.ready ()) {//Perform a read operation, that is ReadLine
This method is often used, but the return is empty, what is the reason for this, look at the Help document, and check the Internet, summarized as follows:
Ready is to see if the stream is prepared to be read, is a non-blocking method, so it returns immediately, because the server is not ready to be read, so it returns immediately, so the read is NULL, then we use while ((str = Reader.readline ())! = NULL) to read it, ReadLine is a blocking method, as long as there is no disconnection, will wait until something returns, then when to return to empty, only read to the end of the data flow, only return null, for example, usually only when the end of the file is read to be empty, As to read the server-side data, is generally not empty, then sometimes we use a specific character to represent the end, on the network, has been waiting for input, even if the other party does not enter anything, just enter, ReadLine will not return null, if I/O interrupt, will return I/O exception, It will still not return NULL unless you are using a data stream that has a fixed length (such as a file data stream, or bytearrayinputstream) rather than a network traffic (blocking mode). In I/O blocking mode, you write a conditional loop that is unreasonable: while ((line = In.readline ()) = null) should be as follows: while (network state)//status can be obtained by catching I/O exceptions when reading data from the client , so if you want to write a multi-user Service program, it's best to use Java.nio, and he will be better at handling this than simply blocking IO.
Similarly, the InputStream available is also non-blocking, in the network, it is likely that the stream delay transmission (rather than arrive, the server side is very easy to use such code, but the application error occurs:
byte[] bytes = new byte[in.available ()];
In.read (bytes);
The result is wrong, because available returns 0
There are a number of workarounds, such as the ability to read one byte at a time, or to read a cache size byte, and each read is blocked. So you can rest assured
Transferred from: http://blog.csdn.net/neusoftware_20063500/article/details/3723176
Know BufferedReader's readline, ready, and InputStream's available