2016-05-14 109 views
0

我被困在试图推进。这个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语句中。 没有用。我是初学者,感谢您的帮助。

+2

读者不会返回null。 – matt

+0

你的代码似乎很容易出错。我们不知道你想要达到什么。如buffer = new String [100];可能会导致溢出,除非您限制为100行。 – vladaman

回答

3

在你server side代码,您已经为line写的递增行是错误的,它必须被纠正为line = line+1;所以整个`服务器端代码必须看起来像下面

line = 0; 
while ((buffer[line] = in.readLine()) != null) { 
    System.out.println(buffer[line]); 
    line++; 
} 
-1

读取字符串到StringBuilder的,而不是 - 少分配,更快,eaasier:直到关闭套接字

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();