Saturday, September 23, 2017

read() method return -1 when reach the End of Stream

read()

The read() method of an InputStream returns an int which contains the byte value of the byte read. Here is an InputStream read() example:
int data = inputstream.read();
You can case the returned int to a char like this:
char aChar = (char) data;
Subclasses of InputStream may have alternative read() methods. For instance, the DataInputStream allows you to read Java primitives like int, long, float, double, boolean etc. with its corresponding methods readBoolean(), readDouble() etc.

End of Stream

If the read() method returns -1, the end of stream has been reached, meaning there is no more data to read in the InputStream. That is, -1 as int value, not -1 as byte or short value. There is a difference here!
When the end of stream has been reached, you can close the InputStream.

@reference_1_tutorials.jenkov.com
Java IO: InputStream

Reading from a Socket

To read from a Java Socket you will need to obtains its InputStream. Here is how that is done:
Socket socket = new Socket("jenkov.com", 80);
InputStream in = socket.getInputStream();

int data = in.read();
//... read more data...

in.close();
socket.close();
Pretty simple, right?
Keep in mind that you cannot always just read from the Socket's InputStream until it returns -1, as you can when reading a file. The reason is that -1 is only returned when the server closes the connection. But a server may not always close the connection. Perhaps you want to send multiple requests over the same connection. In that case it would be pretty stupid to close the connection.
Instead you must know how many bytes to read from the Socket's InputStream. This can be done by either the server telling how many bytes it is sending, or by looking for a special end-of-data character.

@reference_2_tutorials.jenkov.com
Java Networking: Socket

No comments:

Post a Comment