java在两台不同的机器上创建RMI应用程序时,客户端和服务器应该在哪里定义接口客户端或服务器端?
我想用两台笔记本电脑编写一个RMI应用程序,它可以添加两个数字?我制作了一台笔记本电脑作为服务器,另一台笔记本电脑作为客户端。当我们想要定义从远程接口扩展而来的接口时,我应该在哪台机器上定义这个接口—客户端还是服务器端?请帮忙
我使用一台机器制作了一个RMI应用程序,它工作正常。我在同一个包中定义了接口,但当我在不同的机器上工作时,它不工作
public interface AdditionI extends Remote {
public int add(int x ,int y) throws RemoteException;
}
public class Server extends UnicastRemoteObject implements AdditionI {
public Server() throws RemoteException {}
@Override
public int add(int x, int y) throws RemoteException {
return x+y;
}
public static void main(String ar [])throws RemoteException {
try
{
Registry reg = LocateRegistry.createRegistry(2177);
reg.rebind("Add", new Server());
System.out.println("Server is ready");
}
catch(Exception e)
{
System.out.println("Error "+ e);
}
}
}
public class Client {
public static void main(String ar[])throws RemoteException {
try {
Registry reg = LocateRegistry.getRegistry("localhost",2177);
AdditionI ad = (AdditionI)reg.lookup("Add");
System.out.println("REsult:"+(ad.add(10, 5)));
} catch (Exception e) {
System.out.println("Error"+e);
}
}
}
当我在同一台机器上运行此代码时,它工作正常。方法add的结果会显示出来,但在不同的机器上,它会显示以下消息
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: java.lang.ClassNotFoundException:
# 1 楼答案
简单:你需要两边的界面
客户机知道这个接口,基本上它是“唯一”知道的:有一些接口定义了客户机代码可以使用的行为(方法)
服务器知道该接口,并实现它
该接口是“链接”客户机和服务器(概念上)的基本功能。他们都知道有一些接口。客户需要它,所以
另一方面,服务器使用接口将其实现注册为服务。。。然后客户可以打电话
因此,在源代码中基本上有三个不同的部分:
AdditionI
接口的注意:这个例外
java.lang.ClassNotFoundException
是非常基本的。它告诉您,运行某些代码的JVM没有找到某些类换句话说:你的类路径设置不知何故被破坏了。只需研究一下这个例外(你可以找到关于这些基本事物的无穷无尽的文档,例如参见here)。最有可能的是,它归结为:确保一些。类文件位于类路径中。。。在你需要的地方。第一部分已经告诉你该去哪里上课了