【发布时间】:2023-11-18 16:49:01
【问题描述】:
我是 Java RMI 的新手,我只是想运行一个“Hello World”程序(代码显示在消息的末尾)
基本上,我的一台计算机上有一个远程类、一个远程接口和一个服务器类,另一台计算机上有一个客户端类。 我正在尝试使用客户端从服务器获取“hello”消息。 问题是如果我没有远程接口和存根在客户端所在的同一目录中,我将无法编译客户端并使其运行,同时如果我没有,我将无法运行服务器与服务器在同一目录中的那些。
我使用 javac 编译了服务器/远程类/接口,然后使用 rmic 编译器。 “rmic 你好”。
我想知道如何在不必将所有文件都放在两台计算机上的情况下让它工作(这就是我想让它分发的原因)
提前致谢!
代码:
远程接口:
import java.rmi.*;
//Remote Interface for the "Hello, world!" example.
public interface HelloInterface extends Remote {
public String say() throws RemoteException;
}
远程类:
import java.rmi.*;
import java.rmi.server.*;
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
public Hello (String msg) throws RemoteException {
message = msg;
}
public String say() throws RemoteException {
return message;
}
}
客户: 导入java.rmi.*;
public class Client
{
public static void main (String[] argv)
{
try
{
HelloInterface hello= (HelloInterface) Naming.lookup(host); //the string representing the host was modified to be posted here
System.out.println (hello.say());
}
catch (Exception e)
{
System.out.println ("Hello Server exception: " + e);
}
}
}
服务器:
public static void main (String[] argv) {
try {
Naming.rebind ("Hello", new Hello ("Hello, world!"));
System.out.println ("Hello Server is ready.");
} catch (Exception e) {
System.out.println ("Hello Server failed: " + e);
}
}
【问题讨论】: