[英]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 ? 当我从客户端发送字符“ 123456789”时,这正是我在服务器终端中看到的,但是我不应该只看到12345吗?
Why the difference in the behaviour? 为什么在行为上有所不同?
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. 您的客户端被设置为一次只能发送 5个字符,然后刷新-因此,即使InputStreamReader
可能要求的数据更多,但接收到的数据却更少,然后发现它可以满足您对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. 尝试将服务器上的代码更改为一次只能读取3个字符,而不是5 个字符(但是让客户端发送5 个字符),您可能会发现行为有所不同。 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. 基本上,该课程应该是您不想在同一个流上构造多个阅读器-由于缓冲,很难预测将要发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.