jbu
jbu

Reputation: 16131

Server disconnects in Java

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.

Upvotes: 0

Views: 2072

Answers (2)

Powerlord
Powerlord

Reputation: 88796

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500665

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.

Upvotes: 3

Related Questions