2012-02-15 156 views
0

我试图在两个JVM之间发送消息:服务器启动第二个进程。第二个过程是发送消息到服务器,该消息将消息输出到控制台。代码如下:通过Java中的标准输入/输出进行通信

public class Server 
{ 
    public static void main(String[] args) 
    { 
     Process client=null; 
     BufferedReader clientInput=null; 

     try 
     { 
      client=Runtime.getRuntime().exec("java Client"); 
      clientInput=new BufferedReader(new InputStreamReader(client.getInputStream())); 
     } 
     catch(IOException e){} 

     System.out.println("Waiting for the client to connect..."); 

     try 
     { 
      String msg=clientInput.readLine(); 
      System.out.println(msg); 
     } 
     catch(IOException e){} 

     client.destroy(); 
    } 
} 

public class Client 
{ 
    public static void main(String[] args) 
    { 
     BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); 

     try 
     { 
      out.write("Ready\n"); 
      out.flush(); 
     } 
     catch (Exception e){} 
    } 
} 

如果我跑,我得到从服务器,没有输出。最后,沟通应该是双向的。任何帮助不胜感激。

编辑:我没有得到任何错误(只是删除从catch块的打印语句以节省空间)。

回答

1

您在流结束时收到空。客户端正确启动,发送就绪,并结束,所以流结束。

完全正确的行为。如果客户端会自行结束(而不是像在stdin上读取服务器消息那样做其他事情),那么服务器将永远不会收到null。

编辑:永远不要(!!!!!)做到这一点:

catch(IOException e){} 

至少写:

catch(IOException e){ e.printStackTrace() } 

这会告诉你你的错误!

在我的公司,这是代码风格的基本规则之一!

+0

的问题是,所有我收到的是空 - “就绪”从未收到虽然。 – coderino 2012-02-15 16:54:04

+0

我在我的代码中有e.printStackTrace()。正如我上面所说,我只是把它删除,以免混乱太多空间。正如我所说,没有例外。 – coderino 2012-02-16 10:07:48

1

我认为你需要添加一个while循环:

while ((s = in.readLine()) != null && s.length() != 0) 
    System.out.println(s); 
} 
+0

我会尝试 - 谢谢。 – coderino 2012-02-16 10:08:43

相关问题