简体   繁体   English

Java IPC:GUI 和命令行

[英]Java IPC: GUI and Command Line

I would like to implement a command line interface for a Java application.我想为 Java 应用程序实现一个命令行界面。 This wouldn't be too difficult to do, except I would like the command line program to affect the state of another Java GUI program.这不会太难做,除非我希望命令行程序影响另一个 Java GUI 程序的状态。 So for example, I could type:例如,我可以输入:

java CliMain arg1 arg2

And another running GUI instance would perform an appropriate action.另一个正在运行的 GUI 实例将执行适当的操作。

What is the easiest way of implementing something like this?实现这样的事情的最简单方法是什么?

You could have the GUI application listen on a TCP port (on the localhost interface) and the CLI application would connect to it.您可以让 GUI 应用程序侦听 TCP 端口(在localhost接口上),并且 CLI 应用程序将连接到它。

One way to do this would be to use REST over HTTP.一种方法是使用 REST over HTTP。

Another way is through JMX.另一种方法是通过 JMX。 It gives you a lot of stuff "for free" (in the simple case you just implement a bean and register it -- very simple), and is particularly well suited to this task.它为您提供了很多“免费”的东西(在简单的情况下,您只需实现一个 bean 并注册它——非常简单),并且特别适合这项任务。

you can have the GUI application(like an editor) listen on您可以让 GUI 应用程序(如编辑器)监听

1) clipboard event of a certain type 1) 某种类型的剪贴板事件
if the event is of a type that you are interested in, then get the clipboard contents.如果事件是您感兴趣的类型,则获取剪贴板内容。

2) server socket on a certain port 2) 某个端口上的服务器套接字
listen on a server socket.侦听服务器套接字。 when the CLI program starts, it connects to the server socket at a known port, sends info and quits.当 CLI 程序启动时,它连接到已知端口的服务器套接字,发送信息并退出。

3) queue 3) 排队
you can enque from the CLI program and deque from the GUI program.您可以从 CLI 程序入队,也可以从 GUI 程序出队。

if you want to investigate further, many professional editors like emacs use the same mechanism.如果您想进一步调查,许多专业编辑器如 emacs 使用相同的机制。 http://www.emacswiki.org/emacs/EmacsClient http://www.emacswiki.org/emacs/EmacsClient

Your application could be controlled via RMI .您的应用程序可以通过RMI进行控制。 The application would implement a control interface, register its service on localhost and the command line application would get an rmi proxy and call the desired control methods...该应用程序将实现一个控制接口,在本地主机上注册其服务,命令行应用程序将获得一个 rmi 代理并调用所需的控制方法......

Seems hard at first, but when you've tried out you'll quickly see how easy that is.一开始似乎很难,但是当您尝试过之后,您很快就会发现那是多么容易。 And it also supports encryption via SSL .并且它还支持通过SSL 进行加密。 So you could secure your data exchange if there was security relevant data online.因此,如果在线存在安全相关数据,您就可以保护您的数据交换。

The easiest way would be for the GUI to listen for commands on a TCP port.最简单的方法是让 GUI 侦听 TCP 端口上的命令。 The command line would send commands, and the GUI would interpret them.命令行会发送命令,GUI 会解释它们。

Maybe you could do it with named pipes as well, but I'm not sure how you'd go about implementing that in Java.也许你也可以用命名管道来做到这一点,但我不确定你会如何在 Java 中实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM