0

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?

Kalina
  • 5,504
  • 16
  • 64
  • 101
  • You should also remove the isClosed() test. It doesn't do what you think: it only tells you whether you have closed the socket yourself. It's not an EOS test: read() returning -1 tells you that. If you've closed the socket yourself you shouldn't be anywhere near this code in the first place. – user207421 Jul 13 '12 at 17:57

2 Answers2

2

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

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".

Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106