当我尝试运行我的 RMI 示例时出现远程异常。我不明白为什么。 我在不对程序本身或 JVM 进行任何参数的情况下运行该程序。
请帮助我摆脱异常。
非常感谢
这是我得到的异常:
Server exception: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: hello.Hello
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: hello.Hello
这些是我的类(class):
客户端类:
package hello;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
String host = (args.length < 1) ? null : args[0];
try {
Registry registry = LocateRegistry.getRegistry(host);
Hello stub = (Hello) registry.lookup("Hello");
String response = stub.sayHello();
System.out.println("response: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
远程接口(interface):
package hello;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote {
String sayHello() throws RemoteException;
}
最后是服务器:
package hello;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Hello {
public Server() {}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
try {
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// Bind the remote object's stub in the registry
Registry registry = LocateRegistry.getRegistry("localhost");
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
最佳答案
注册表或客户端或两者都找不到异常中指定的类。有几种可能的解决方案:
在执行注册表和客户端时将该类包含在类路径中。以及它依赖的所有类,递归直到关闭。
使用
LocateRegistry.createRegistry()
从服务器 JVM 内部启动注册表,它解决了类路径问题,并仅在客户端的类路径中提供必要的类。使用代码库功能确保所有系统组件都可以访问所需的服务器端类。
关于java - RMI 远程异常。 RMI 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017756/