通过Java中的标准输入/输出进行通信
我试图在两个JVM之间发送消息:服务器启动第二个进程。第二个过程是向服务器发送消息,服务器将消息打印到控制台。代码如下:通过Java中的标准输入/输出进行通信,java,io,jvm,pipe,Java,Io,Jvm,Pipe,我试图在两个JVM之间发送消息:服务器启动第二个进程。第二个过程是向服务器发送消息,服务器将消息打印到控制台。代码如下: public class Server { public static void main(String[] args) { Process client=null; BufferedReader clientInput=null; try { client=Runtim
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();
}
}
及
如果我运行它,我将从服务器获取作为输出的null。最后,沟通应该是双向的。非常感谢您的帮助
编辑:我没有收到任何错误(只是从catch块中删除了print语句以节省空间)。您在流的末尾收到null。客户机正确地启动、发送就绪并结束,因此流结束 完全正确的行为。如果客户端结束自身(而是执行其他操作,如在stdin上读取服务器消息),服务器将永远不会收到空值 编辑:永远不要(!!!!!)这样做: 至少写下:
catch(IOException e){ e.printStackTrace() }
这将显示您的错误
在我的公司,这是代码风格的基本规则之一 我认为您需要添加一个while循环:
while ((s = in.readLine()) != null && s.length() != 0)
System.out.println(s);
}
问题是,我接收到的所有内容都是空的——但从未接收到“Ready”。正如我上面所说,我只是删除了它,这样就不会占用太多的空间。正如我所说,没有抛出异常。
catch(IOException e){ e.printStackTrace() }
while ((s = in.readLine()) != null && s.length() != 0)
System.out.println(s);
}