如何翻译以下对话:
- Application1:“您好,Application2,我需要要分析的单词列表”
- 应用程序2:“这是:
String[]
”
进入Java代码,两个进程驻留在同一台机器上?
我见过this question和其他相关的,但答案对我来说并不是很清楚。 因此,我认为像监听器这样的东西可能会有用。此外,我更喜欢一些非常简单的东西,不涉及使用复杂的框架(例如 Spring),正如前面的问题所建议的。
最佳答案
Java RMI (远程方法调用)可能会这样做。
(不再需要 rmic
编译器 - 如果您仍然发现这样一个过时的示例。)
较新版本的 RMI 使用接口(interface)、实现类和端口来进行发现。
我用它来实现单个实例类:如果启动应用程序的第二个实例,它会在端口上发现其类,如果已被占用,可能会搜索另一个端口,并将其命令行委托(delegate)给第一个端口其自身的实例。
没有管理员权限可能会很棘手。
客户端应用程序:
public static void main(String[] args) {
try {
DictServer server = (DictServer)
Naming.lookup("//localhost:1024/dictserver");
String[] words = server.getWords();
System.out.println(Arrays.toString(words));
} catch (RemoteException | MalformedURLException
| NotBoundException ex) {
ex.printStackTrace();
}
}
通用接口(interface):
public interface DictServer extends Remote {
public String[] getWords() throws RemoteException;
}
服务器应用程序:
public class DictServerImpl extends UnicastRemoteObject implements DictServer {
public DictServerImpl() throws RemoteException {
}
@Override
public String[] getWords() throws RemoteException {
return new String[] { "unu", "du", "tri", "kvar", "kvin", "ses" };
}
}
public class Main {
public static void main(String[] args) {
try {
int port = 1024;
Registry registry = LocateRegistry.createRegistry(port);
registry.rebind("dictserver", new DictServerImpl());
} catch (RemoteException ex) {
ex.printStackTrace();
}
}
}
此处使用端口 1024 并假设在同一台计算机上运行。
关于java - 连接两个 Java 应用程序的适当方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24627279/