1

In a loop, this code runs (server side):

try {
        BufferedInputStream is = new BufferedInputStream(cnn.getInputStream());
        InputStreamReader isr = new InputStreamReader(is);
        int character;
        StringBuffer process = new StringBuffer();
        while ( (character = isr.read()) != 13) {
          process.append( (char) character);
        }
        println("Input: " + process.toString());
} catch (Exception e) { }

the client is not sending anything, but process.toString() outputs infinite question marks. the variable is outputs this: java.io.InputStreamReader@510ebe18 (the last number always changes)

Isn't the input supposed to be empty and fall back to catch block if the client doesn't send anything?

What am i doing wrong?

note: the while-loop goes on forever because there is no end to the input, i was able to see the question marks comming out by putting a limit of 100 characters to the process variable.

4
  • 2
    Is the client closing the socket? Because if so, isr.read() will keep on returning -1... Oh, and printing the result of InputStreamReader.toString() is never going to do anything useful. Commented Oct 5, 2013 at 11:20
  • You've slightly changed that code before you posted it. Eg process is called thread_process Commented Oct 5, 2013 at 11:20
  • yes, i tend to strip and clean up my code before posting it in order to avoid chaos/confusion. Commented Oct 5, 2013 at 11:23
  • currently the client does not close the socket, and i want to convert InputStreamReader to an array by converting it to a string first. is this not the right way to do that? Commented Oct 5, 2013 at 11:24

1 Answer 1

1

? marks are probably because the stream source is returning -1 to indicate the end of the stream. But the while loop is waiting for a carriage return.

The read call is blocking and will wait for the input. Only if it detects the end of the stream or on some erroneous condition does it throw an exception.

I presume you are reading lines. It would be efficient to use BufferedReader instead of reading it byte by byte.

So, if you were reading from standard input. You could do something like :

BufferedReader reader = new BufferedReader(
   new InputStreamReader(new BufferedInputStream(System.in)));

try {
    StringBuilder result = new StringBuilder();

    for (String line = null; (line = reader.readLine()) != null;) {
        result.append(line);
    }
    //process result
    System.out.println(result);
} catch (IOException e){
    e.printStackTrace();
}

The toString method of InputStreamReader is not overloaded.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.