我被困在試圖推進。這個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