Why a new InputStream will still read what is left over from an old InputStream?

Well please see this question and Jon Skeet's answer first.

This time I have this server:

public class SimpleServer {
    public static void main(String[] args) throws Exception {

        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("Server Socket created, waiting for client...");

        Socket accept = serverSocket.accept();
        InputStreamReader inputStreamReader = new InputStreamReader(accept.getInputStream());

        char[] chars = new char[5];

        System.out.println("Client connected, waiting for input");

        while (true) {
            inputStreamReader.read(chars,0,chars.length);
            for (int i=0;i<5;i++) {
                if(chars[i]!='\u0000') {
                    System.out.print(chars[i]);
                }
            }
            inputStreamReader = new InputStreamReader(accept.getInputStream());
            chars = new char[5];
        }

    }
}

And when I send the characters "123456789" from the client, this is what I exactly see in the Servers terminal, but should not I be seeing only 12345 ?

Why the difference in the behaviour?

Jon Skeet
people
quotationmark

Your client has been set up to only send 5 characters at a time, and then flush - so even though the InputStreamReader probably asked for more data than that, it received less, and then found that it could satisfy your request for 5 characters with what it had got.

Try changing the code on the server to only read 3 characters at a time instead of 5 (but leave the client sending 5) and you may well see a difference in behaviour. You may not, mind you - it will depend on a lot of different things around the timing of how the data is moving around.

Basically the lesson should be that you don't want to be constructing multiple readers over the same stream - it becomes hard to predict what will happen, due to buffering.

people

See more on this question at Stackoverflow