为什么新的InputStream仍会读取旧的InputStream剩余的内容? [英] Why a new InputStream will still read what is left over from an old InputStream?

查看:124
本文介绍了为什么新的InputStream仍会读取旧的InputStream剩余的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅问题和Jon Skeet的回答。

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

这次我有这个服务器:

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];
        }

    }
}

当我从客户端发送字符123456789,这是我在服务器终端中看到的,但我不应该只看到12345?

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 ?

为什么行为不同?

推荐答案

您的客户有设置为一次仅发送 5个字符,然后刷新 - 所以即使 InputStreamReader 可能询问对于更多的数据,它收到的更少,然后发现它可以满足你的5个字符的请求。

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.

尝试更改服务器上的代码只能一次读取 3 字符而不是5(但让客户端发送5),你可能会看到行为上的差异。你可能不,请注意 - 它将取决于数据如何移动的时间周围的许多不同的事情。

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.

这篇关于为什么新的InputStream仍会读取旧的InputStream剩余的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆