Question

Can someone explain to me why this works just fine with in.available()>0 commented out, but when I put it back in it breaks?

mySocket = new Socket("blahblah", 12345);
BufferedInputStream in = new BufferedInputStream(mySocket.getInputStream());
....
char result[] = new char[length];       
for (int i = 0; i < length && !mySocket.isClosed() /*&& in.available()>0*/; i++){
    result[i] = (char)in.read();
}

More specifically: I'm making an Android app where a user can search for a term, that search is sent to some thingy in interspace, I get back results in xml form, and do stuff with them. When the xml I get back is small enough (see "length" in code above), the code works just fine with in.available()>0 left in. But if the length is large, in.available() returns 0. But with that commented out, everything continues to run smoothly.

Why is that? And is it something I need to worry about and fix?

Was it helpful?

Solution

I think the reason in.available() == 0 when the data is large is because it hasn't had a chance to write it to your socket yet. You shouldn't need to use in.available(). Also, I wouldn't suggest reading a single char at a time, that will be really slow with a lot of data and VERY chatty over the network. Consider reading in a byte array of size "length".

OTHER TIPS

in.available() lets you know if you can read data at that moment without blocking. As Sockets have a stream of data, it may not available immediately but in a short time. e.g. if you have a 1 Gbit connection, full packets will be no closer than 15 micro-seconds which is long time for a computer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top