gpt4 book ai didi

java - 为什么新的 InputStreamReader 不会读取控制台中的剩余字符?

转载 作者:行者123 更新时间:2023-12-01 11:56:21 32 4
gpt4 key购买 nike

所以我有一个用 Java 编写的非常简单的服务器:

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());
int read;
System.out.println("Client connected, waiting for input");
while ((read = inputStreamReader.read()) != -1) {
System.out.print((char) read);
}
}
}

这是我用来连接它的代码:

public class SimpleClient {

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

Socket socket = new Socket("localhost",8888);
OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());

InputStreamReader inputStreamReader;
char[] chars = new char[5];

while (true) {
System.out.println("Say something: ");
inputStreamReader = new InputStreamReader(System.in);
inputStreamReader.read(chars);
int x = 0;
for (int i=0;i<5;i++) {
if(chars[i]!='\u0000') {
x++;
}
}
outputStream.write(chars,0,x);
outputStream.flush();
chars = new char[5];
}

}

}

现在,当我在客户端的终端中输入这样的内容时:

123456789

我将在服务器的终端中看到:

Server Socket created, waiting for client...
Client connected, waiting for input
12345

但是,当我按如下方式更改客户端时:

public class SimpleClient {

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

Socket socket = new Socket("localhost",8888);
OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());

InputStreamReader inputStreamReader = new InputStreamReader(System.in);
char[] chars = new char[5];

while (true) {
System.out.println("Say something: ");
inputStreamReader.read(chars);
int x = 0;
for (int i=0;i<5;i++) {
if(chars[i]!='\u0000') {
x++;
}
}
outputStream.write(chars,0,x);
outputStream.flush();
chars = new char[5];
}

}

}

然后对于相同的输入,我会看到:

Server Socket created, waiting for client...
Client connected, waiting for input
123456789

我的问题是,System.out 是一个静态变量,在本例中它已经打开并连接到终端。为什么创建新的InputStreamReader对象时终端中的信息会丢失?相同的终端被传递给对象,不是吗?

最佳答案

Why is the information in the terminal lost when a new InputStreamReader object is created?

当您在 InputStreamReader 上调用 read() 时,它允许(并且通常会)从流中读取比您实际请求的更多的数据,并存储其余的在缓冲区中,以满足稍后的读取调用。我怀疑整个文本行实际上已被第一个 InputStreamReader 读取,因此当您为同一流构造第二个 InputStreamReader 时,没有任何内容可供它读取,您必须输入更多文本才能让它执行任何操作。

关于java - 为什么新的 InputStreamReader 不会读取控制台中的剩余字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28419617/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com