1

I'm using the class DataInputStream to read from a Socket. I must use the readByte (not readLine) because the input does not necessarily in String format. The problem is I must wait the end of the stream to call a function and I couldn't detect it.

The code:

reader = new DataInputStream(socket.getInputStream());
byte dt;            

String cmd = "";
while( (dt = reader.readByte()) >= 0){
    cmd += (char)dt;

    if( /* end of the stream reached */ ){ 
        processInput(cmd);
    }  
}
System.out.println("End of the loop");

The problem is I don't know how to write this if. And, the end of the loop is not being reached when the Stream ends, the proof of this is that the phrase "End of the loop" is never being printed, so it is just stuck on the loop

1 Answer 1

4

This is documented at readByte()

Throws:
EOFException - if this input stream has reached the end.

So in order to see end of file, you must use try/catch

try {
    while(true){
        cmd += (char) reader.readByte();
    }
} catch (EOFException e) {
    // handle EOF
}

/* end of the stream reached */
processInput(cmd);

System.out.println("End of the loop");

An alternative would be to use one of the read() functions, which return -1 when reaching end of file, e.g.

int dt;
while ((dt = reader.read()) >= 0) {
// ...
}

Using one of the other read(...) functions could be more efficient, since they return a buffer full of input.

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

1 Comment

It should. Are you sure the other end of the socket is closed?

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.