2010-01-18 63 views
1

我有2个重要的类(客户端和服务器),我会写在我的文本区域的东西,通过点击发送按钮,我会调用客户端类的有效方法,我将文本发送到我的客户端类,每事情是好的,该文本也将被打印在服务器控制台上,但我不能回应从服务器到客户端的文本,请帮助我谢谢。它不会从服务器返回任何东西!

客户端类:(其中的一部分)

os = new PrintWriter(c.getOutputStream(), true); 


is = new BufferedReader(new InputStreamReader(c.getInputStream())); 

public static void active() { 

String teXt = MainClient.getText(); 

os.println(teXt); 

String line = is.readLine(); 
     System.out.println("Text received: " + line); 
     os.flush(); 
     is.close(); 
     is.close(); 
     c.close(); 

服务器类:(其中的一部分)

 BufferedReader streamIn = new BufferedReader(new InputStreamReader(client.getInputStream())); 
     PrintWriter streamOut =new PrintWriter(client.getOutputStream()); 
     boolean done = false; 
     String line =null; 
     while (!done) { 

      line = streamIn.readLine(); 
      if (line.equalsIgnoreCase("bye")) { 
       done = true; 
      } else { 
       System.out.println(line); 
       streamOut.println(line); 
      } 
     } 

     streamIn.close(); 
     client.close(); 
     server.close(); 
+0

另外这是多线程的客户机/服务器应用程序。 – Johanna 2010-01-18 08:29:58

+0

Johanna,这是你第三次问这个问题。我建议你谷歌的“EchoClient”或“EchoServer”找到一个工作的例子,围绕它建立你的代码。粘贴一吨代码,然后期望人们为你调试并不能很好地利用任何人的时间。 – Adamski 2010-01-18 09:05:05

+0

非常感谢,问题已解决[:-)] – Johanna 2010-01-18 12:08:53

回答

1

实际上Nettogrof会以正确的方式,但你也必须刷新服务器端:

 line = streamIn.readLine(); 
     if (line.equalsIgnoreCase("bye")) { 
      done = true; 
     } else { 
      System.out.println(line); 
      streamOut.println(line); 
      streamOut.flush(); // or ...checkError(); 
     } 

或刚刚创建自动冲洗的PrintWriter的设置为true:

PrintWriter streamOut = new PrintWriter(client.getOutputStream(), true); 

一个注意:您还应测试readLine()是否返回null,因为客户端将关闭连接而不发送“再见”。

第二注:为PrintWriter的情况下,从来没有引发IOException,你应该测试是否有错误调用checkError(),这也刷新流。

+0

非常感谢您的正确答案! – Johanna 2010-01-18 12:09:19

0

如何经常被读入的输入流?从代码看,它似乎只有一次读取,可能在从服务器发送任何内容之前,就是这样。如果您打算使用您采取的方法,您可能必须对服务器进行更一致的轮询。

喜欢的东西:

while (line = is.readLine() != null) { 
    System.out.println("Text received: " + line); 

}

+0

我已经完成了它,但它仍然没有在客户端的控制台上返回。 – Johanna 2010-01-18 08:05:32

1

你需要 “os.flush();” 读取服务器应答之前。

因为根据您的客户端代码,你准备文字与

String teXt = MainClient.getText(); 

os.println(teXt); 

然后你等待服务器答复发送:

String line = is.readLine(); 
System.out.println("Text received: " + line); 

然后您将文本发送到服务器:

os.flush(); 

尝试:

String teXt = MainClient.getText(); 

os.println(teXt); 
os.flush(); 
String line = is.readLine(); 
System.out.println("Text received: " + line); 
+0

它不工作! – Johanna 2010-01-18 08:29:32

+0

实际上PrintWriter是在启用autoFlush的情况下创建的:'os = new PrintWriter(c.getOutputStream(),true);'所以在println之后不需要调用flush。 – 2010-01-18 11:04:35

0

服务器代码的实现是错误的,streamIn,客户端和流输出永远不会因为无限循环的闭合。

请参阅medopal提及的文章以获取更多帮助。