Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Detect Closed Stream

I have a general socket implementation consisting of an OutputStream and an InputStream.

After I do some work, I am closing the OutputStream.

When this is done, my InputStream's read() method returns -1 for an infinite amount of time, instead of throwing an exception like I had anticipated.

I am now unsure of the safest route to take, so I have a few of questions:

  • Am I safe to assume that -1 is only returned when the stream is closed?
  • Is there no way to recreate the IO exception that occurs when the connection is forcefully broken?
  • Should I send a packet that will tell my InputStream that it should close instead of the previous two methods?

Thanks!

like image 896
Derek Avatar asked Apr 10 '11 02:04

Derek


1 Answers

The -1 is the expected behavior at the end of a stream. See InputStream.read():

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

You should still catch IOException for unexpected events of course.

like image 109
WhiteFang34 Avatar answered Sep 23 '22 07:09

WhiteFang34