我被迫试图前进。当从套接字接收线路时,这个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语句中。 什么都行不通。我是初学者,谢谢你的帮助。
答案 0 :(得分:1)
在server side
代码中,您为line
编写的递增行是错误的,必须更正为line = line+1;
,因此整个`服务器端代码必须如下所示
line = 0;
while ((buffer[line] = in.readLine()) != null) {
System.out.println(buffer[line]);
line++;
}
答案 1 :(得分:-1)
将字符串读取到StringBuilder - 减少分配,更快更轻松:
StringBuilder builder = new StringBuilder();
String aux = "";
BufferedReader pinput = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((aux = pinput.readLine()) != null) {
builder.append(aux);
}
String text = builder.toString();