How to identify end of InputStream in java

It’s looking for more data because nothing’s told it that there won’t be more data. The other end of the network could send more data at any time.

It’s not clear whether you’re designing the client/server protocol or just trying to implement it, but typically there are three common ways of detecting the end of a message:

  • Closing the connection at the end of the message
  • Putting the length of the message before the data itself
  • Using a separator; some value which will never occur in the normal data (or would always be escaped somehow)

Personally I favour length-prefixing when possible; it makes the reading code significantly simpler, but still allows multiple messages on the same connection.

(Additionally, I agree with Daniel that you should be using the overload of read which reads a whole buffer at a time, instead of a single byte. This will be much more efficient – but doesn’t fundamentally change the nature of your current issue.)

Leave a Comment