4

I'm using java's InputStreamReader read() function. When I reach the end of the input stream i'm supposed to get in to my int variable the value of -1, but instead it goes to block. Why don't I get a -1 at the end of the input stream? (i've debugged it letter by letter making sure it is actualy the end of the input and that the connection socket is alive).

Is using the ready() function a good solution by doing:

if (isr.ready())
    currCharVal = isr.read();

Thanks in advance, Guy.

Guy
  • 41
  • 2
  • What is the underlying `InputStream`? Can you post more code please? – dorsh Jan 21 '12 at 15:14
  • Define the "end" of an input stream--streams can be anything, including something like a never-ending network connection. How it's handled depends on the stream type. – Dave Newton Jan 21 '12 at 15:15
  • "... connection socket is alive" - as long as the socket is not closed, you haven't reached the end of the input stream as far as the socket is concerned. – Mat Jan 21 '12 at 15:16
  • I am getting an httprequest from cURL. I use a tokenizer to read 128 chars per token. While reading the last token, the isr.read() just gets in to block mode because its finished getting the message. – Guy Jan 21 '12 at 15:19
  • @Guy That means cURL, for whatever reason, does not close the stream you're reading from. – nos Jan 21 '12 at 15:20
  • @nos I want the connection to be alive because I'm supposed to send a response back (built on the input). I want to know somehow that once all the httprequest has been sent I can stop. I see that waiting for -1 is not the solution because that happens only when connection is disconnected. – Guy Jan 21 '12 at 15:35
  • I have solved the problem. I'm using setSoTimeout to wait a few seconds if i'm on a read() block. This way if no information is sent, i just submit the token I created up untill the block and continue on to process the info I have. – Guy Jan 21 '12 at 16:49

1 Answers1

4

This would happen if the other end is not closing the connection. When the socket is closed, read() will return a -1.

Using ready and available is rather unpredictable in my experience. I would just read(byte[]) until the end is reached and expect the other end to close when finished.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I need to keep the connection alive because an answer is generated according to the input. So I understand why -1 is not a good way to know when the input is complete. Is there another way to determine when the client has stopped sending the httprequest data in my tokenizer? – Guy Jan 21 '12 at 15:48
  • I would assume you are given the Content Length to know when it has finished that response. You can't send a `-1` does a stream. – Peter Lawrey Jan 21 '12 at 17:20