开发者

Java Opening external scripts AND giving input/getting output

Alright, still working on a science project involving the testing of the speeds of data sending over the internet with different languages. My teacher doesn't seem to think this is difficult enough, and wants me to run a main Java program to control the clients.

I have figured out how to run external files (Still having trouble with spaces in the file name, though) and am fine with that. My trouble is that I need to somehow commucate to the opened client (I've got Python, C, C++, Java, and Ruby client) the number of times to test, and I need to get the dataset obtained through the testing.

In the end, I need to find out how to send input to Python, C, C++, Java, and Ruby scripts from java AND gather output from them to put into java. As a last resort, I can probably have a text file act as a mediator between the main java program and each of the clients. This is not a very elegant 开发者_StackOverflow中文版solution, so I'd rather avoid it.


You might be looking for JNI - Java Native Interface. JNI will certainly fulfill your teacher's request for difficulty. JNI allows Java code to call code within other languages and get responses back as if you were calling a Java method. The biggest issue I know of with JNI is that crashes within the native (C, C++, etc.) code will crash your Java program as well. JNI will make what is currently an external script internal code to your application, and is quite possibly more difficulty than you need.

For a simpler solution, you may want to look into the ProcessBuilder class in Java. For example:

ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();
InputStream is = p.getInputStream();
// use process p's input stream is to provide input to your process here
OutputStream os = p.getOutputStream();
// use process p's output stream to get the results here


You might consider using some cross-language API to message between running instances of each of Java, C/C++, Ruby and Python.

  • Spread (seems like there's no Ruby support)
  • RabbitMQ (AMQP) Supports all your listed languages and then some.
  • DBus Supports all your listed languages and then some.
  • Apache Thrift Supports all your listed languages and then some.
  • HTTP and Google ProtocolBuffers Supports all your listed languages and then some.

It will be a bit more complex than using text files as an intermediary, but probably more performant and extensible.

//Nicholas

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜