简体   繁体   中英

Java reading from socket

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.

? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM