两个独立的 Java 桌面应用程序之间的通信

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1680898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:20:34  来源:igfitidea点击:

Communication between two separate Java desktop applications

javaipc

提问by William

I'm looking to develop two separate (but related) Java desktop applications.

我希望开发两个独立(但相关)的 Java 桌面应用程序。

I want the ability for one application to trigger the other, passing in data that can then be edited and passed back, i.e. the communication will be two way. If the other application is already running I want them to just communicate, i.e. I dont want to just pass arguments over the command line, etc.

我希望一个应用程序能够触发另一个应用程序,传入可以编辑和传回的数据,即通信将是两种方式。如果另一个应用程序已经在运行,我希望它们只是通信,即我不想只通过命令行传递参数等。

Generally speaking, what strategies/techniques should I be looking at in order to achieve this?

一般来说,为了实现这一目标,我应该考虑哪些策略/技术?

采纳答案by mhaller

To show how easy it is to let two applications communicate with each other, check out this network-clipboard demo using JGroups. Just start two instances and begin dropping files into one of them. The second instance will instantly show the same files.

为了展示让两个应用程序相互通信是多么容易,请查看这个使用 JGroups 的网络剪贴板演示。只需启动两个实例并开始将文件放入其中一个。第二个实例将立即显示相同的文件。

import java.io.Serializable;
import java.awt.*;
import java.awt.datatransfer.*;
import javax.swing.*;
import org.jgroups.*;

public class JGroupsTest {

    public static void main(String[] args) throws Exception {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(500, 300);
        final DefaultListModel listModel = new DefaultListModel();
        final JList panel = new JList(listModel);
        panel.setBackground(new Color(128, 0, 40));
        panel.setForeground(new Color(240, 240, 240));
        frame.add(panel);
        System.setProperty("java.net.preferIPv4Stack", "true");
        final JChannel channel = new JChannel("udp.xml");
        channel.connect("networkclipboard");
        channel.setReceiver(new ReceiverAdapter() {
            @Override
            public void viewAccepted(View newView) {
                frame.setTitle("Network Clipboard - " + channel.getLocalAddress());
            }

            @Override
            public void receive(Message msg) {
                listModel.addElement(msg.getObject());
            }
        });

        panel.setTransferHandler(new TransferHandler() {
            @Override
            public boolean importData(JComponent comp, Transferable t) {
                DataFlavor[] transferDataFlavors = t.getTransferDataFlavors();
                for (DataFlavor flavor : transferDataFlavors) {
                    try {
                        Object data = t.getTransferData(flavor);
                        if (data instanceof Serializable) {
                            Serializable serializable = (Serializable) data;
                            Message msg = new Message();
                            msg.setObject(serializable);
                            channel.send(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return super.importData(comp, t);
            }

            @Override
            public boolean canImport(TransferSupport support) {
                return true;
            }

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
                return true;
            }

        });
    }

}

回答by BalusC

They could each listen on a Socket. This tutorialis good to get started.

他们每个人都可以收听Socket. 本教程非常适合入门。

回答by Mark

To keep things simple why not just use plain TCP sockets?

为了简单起见,为什么不使用普通的 TCP 套接字呢?

回答by Jé Queue

You should also consider good ol' classic RMI.

您还应该考虑使用经典的 RMI。

回答by osanchezmon

Try to communicate with SocketCommunication, even if the application are in the same machine.

尝试与 SocketCommunication 通信,即使应用程序在同一台机器上。

Here can find more info about how to do it(Sun/Java documentation).

这里可以找到有关如何操作的更多信息(Sun/Java 文档)。

回答by 0x808080

I second Socket communication and RMI. RMI is a little more involved but is more intuitive to a programmer. It depends on what type of information you are sending though. Pushing raw bytes over to another machine might make more sense then running the RMI server and dealing with all that jazz...

我第二个Socket通信和RMI。RMI 有点复杂,但对程序员来说更直观。不过,这取决于您发送的信息类型。将原始字节推送到另一台机器可能比运行 RMI 服务器并处理所有爵士乐更有意义......

回答by Carl Smotricz

  • The "Enterprise" way to go would be to run these apps in a Java EE server or at least in a Spring framework. It's also probably vastly overkill.

  • If a bunch of data needs to be communicated, then RMI will do it.

  • If you're not afraid to hack your own protocol, data structure and error handling, you can set up server and client sockets and communicate through those.

  • I think there's a certain crude appeal to the alternative of communicating via a file in a common directory (setting up your own protocol of who writes or erases the file when), or via a shared database. Low-tech, not extremely fast, but very simple and reliable. And it's fairly easy to monitor "communication" from the outside.

  • “企业”的方式是在 Java EE 服务器或至少在 Spring 框架中运行这些应用程序。这也可能太过分了。

  • 如果一堆数据需要通信,那么 RMI 会做。

  • 如果您不害怕破解自己的协议、数据结构和错误处理,您可以设置服务器和客户端套接字并通过它们进行通信。

  • 我认为通过公共目录中的文件(设置您自己的协议来确定何时写入或删除文件)或通过共享数据库进行通信的替代方案具有某种粗略的吸引力。技术含量低,速度不是很快,但非常简单可靠。从外部监控“通信”相当容易。

回答by pgras

Have a look at JavaGroups, it will solve your communication problem and also help you to detect if the other app is running. If the app isn't running you will have to launch a new JVM for it with java.lang.Runtime.exec()...

看看JavaGroups,它将解决您的通信问题,并帮助您检测其他应用程序是否正在运行。如果应用程序没有运行,你将不得不使用 java.lang.Runtime.exec() 为它启动一个新的 JVM...

回答by tinkertime

Depending on what style of communication you're looking for (high latency, lots of data, etc.) and whether or not this system may expand past simply 2 java systems, a possibility could be a messaging system using a middleware solution such as Tibco SmartSockets.

根据您正在寻找的通信方式(高延迟、大量数据等)以及该系统是否可以扩展到超过 2 个 Java 系统,一种可能性可能是使用中间件解决方案的消息传递系统,例如 Tibco智能插座。

Any more info on your setup and expectations would help.

有关您的设置和期望的更多信息会有所帮助。

回答by Yan Pujante

It depends what kind of communication you want to do between the 2 apps. If you use sockets or RMI for example, both applications need to be up in order for the communication to happen. If the kind of communication you want to do can be more asynchronous then you can use more of a messaging based approach.

这取决于您想在这两个应用程序之间进行什么样的通信。例如,如果您使用套接字或 RMI,则两个应用程序都需要启动才能进行通信。如果您想要进行的通信类型可以更异步,那么您可以使用更多基于消息传递的方法。

For example, ZooKeeper allows you to implement pretty much anything you want on top of very simple yet powerful primitives. This page (http://hadoop.apache.org/zookeeper/docs/current/recipes.html) explains how to build higher level constructs with ZooKeeper.

例如,ZooKeeper 允许您在非常简单但功能强大的原语之上实现几乎任何您想要的东西。此页面 ( http://hadoop.apache.org/zookeeper/docs/current/recipes.html) 解释了如何使用 ZooKeeper 构建更高级别的构造。

The drawback is that you need another system. If you use JGroups for example then you don't.

缺点是您需要另一个系统。例如,如果您使用 JGroups,那么您就不用。

Hope this helps

希望这可以帮助