java - Android: How Reliable is InputStream.read() and its "-1" return? -


my question related method inputstream.read() - socket programming.

every source have found states when server or client closes connection, "-1" returned.

but, "what if", saying, "what if" connection is closed read() not return "-1"? rely on else's code. reason worried because in order read remote end's input, 1 have create infinite loop , have been thought stay away infinite loops. java however, looks not have choice! here sample:

int b = 0;     while (true)     {       b = inputstream.read()       if (b == -1) break; // connection closed     } 

or

 while (b > -1)  b = inputstream.read() 

what if happens, , -1 never becomes true? 1 end in infinite loop increasing temperature of someone's device , wasting cpu cycles! how can 1 certain?

references: [http://developer.android.com/reference/java/io/inputstream.html#read%28%29][1] , [http://docs.oracle.com/javase/6/docs/api/java/io/inputstream.html#read%28byte[],%20int,%20int%29][2]

i want have fail-safe check. have done in loop check whether socket has become null , if so, break loop.

 while (b > -1)     {       b = inputstream.read()        if (socket == null) break;       if (outputstream == null) break;     } 

what else can ensure loop exists in case "-1" never becomes true?

one end in infinite loop increasing temperature of someone's device , wasting cpu cycles!

this not true , think major part of why ask question. read() not busy wait (i.e ask cpu constantly) if doesn't have read. in practice there wouldn't major problem if -1 isn't returned.

read() throws ioexception in case goes wrong reading (for example if inputstream closed). making sure have have loop inside try-block checking -1 more enough making sure it'll out of loop, such:

try {     int b;     while ((b=inputstream.read() > -1)     {        //do     } } catch (ioexception e) {     e.printstacktrace(); } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -