views:

356

answers:

2

Related posts didn't answer my question.

I have a server which does something like:

EVERY TWO SECONDS DO: 
if the inputstream is not null {
     if inputStream.available() is 0 
     {
          return 
     }
     print "handling input stream"
     handleTheInputStream(); 
}

Even after my client disconnects, the server doesn't recognize it through an IOException. The other post said that I would see an End-of-Stream character. However, that is not the case, since after my client disconnects I never see "handling input stream" which indicates that no data is available.

Perhaps something is wrong with the way I currently understand how this works.

Please help.

+3  A: 

Don't use available() - that says whether or not there's currently data available, not whether there will be data available in the future. In other words, it's the wrong tool to use to detect disconnection.

Basically you should call read() (and process the data) until it returns -1, at which point it means the client has disconnected.

Jon Skeet
Read returns -1 when the client has disconnected.
andri
The problem is that I do not want to change existing code in the server since I didn't write it. I CAN change it, but I'd like to know there isn't any other way to do it before I request to change. Changing would require lots of regression testing.
jbu
@andri: Thanks, fixed.
Jon Skeet
Addition: I am simply changing the handleInputStream() method.
jbu
@jbu: Well, we don't know anything else about the code - but using available() is certainly not the way to detect disconnects. I can't remember the last time I saw a *valid* use for available() to be honest.
Jon Skeet
Yes, the API for available() is not clear to me. I am not sure what "Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream." means exactly and what the implications are.
jbu
Basically it says "is there any data available *right now*". Absence of data right now doesn't mean the stream has finished. On the other hand, it *might*. You really need to read from the stream, and if it returns -1 then the stream has *definitely* finished.
Jon Skeet
+1  A: 

If this is done using sockets, you may want to check the Socket class's various instance methods, such as isClosed() or isInputShutdown().

Of course, this assumes that the method operating on this stream has access to the Socket object and not just the InputStream.

R. Bemrose