我被困在试图推进。这个while循环似乎在从套接字接收到线路时会挂起。Java,BufferedReader在while循环中的问题
下面的代码的服务器端:
out = new PrintWriter(socketcliente.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socketcliente.getInputStream()));
//receive and shows client data
linea = 0;
while ((buffer[linea] = in.readLine()) != null) {
System.out.println(buffer[linea]);
linea = linea+1;
}
//asks for a command and sends it to client
System.out.println("Enter remote command");
while ((input = scanner.nextLine()) != null) {
out.println(input);
}
和这里的客户端:
out = new PrintWriter(socketcliente.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socketcliente.getInputStream()));
//sends a limited amount of lines to the server
linea = 0;
while (buffer[linea] != null) {
out.println(buffer[linea]);
linea = linea+1;
}
//receive the command from server, executes and save output for sending to the server
while ((comandor = in.readLine()) != null) {
proceso = Runtime.getRuntime().exec(comandor);
pinput = new BufferedReader(new InputStreamReader(proceso.getInputStream()));
buffer = new String[100];
linea = 0;
while ((psalida = pinput.readLine()) != null) {
buffer[linea] = psalida;
linea = linea+1;
}
}
服务器打印接收到数据后,它什么都不做,也没有退出while循环。必须将数据发送回客户端。我正在使用PrintWriter和BufferedReader。
编辑:更完整的代码,以了解我正在尝试。命令执行和输出保存运行正常,问题是接收服务器中的数据,它获取所有数据,但在结束时停止并且不退出第一个while循环。我怎样才能让它退出循环?我试过消息后发送来自客户端的空字节,或“退出文本”,该服务器可以理解,如:
while ((buffer[linea] = in.readLine()) != null && (buffer[linea] = in.readLine()) != "quit")
我迷路了,并没有发现该怎么办。
所有这些都在try语句中。 没有用。我是初学者,感谢您的帮助。
读者不会返回null。 – matt
你的代码似乎很容易出错。我们不知道你想要达到什么。如buffer = new String [100];可能会导致溢出,除非您限制为100行。 – vladaman