在两台不同的计算机上创建RMI应用程序时,客户端和服务器应在哪里定义接口客户端或服务器端?

时间:2019-07-01 18:01:02

标签: java interface rmi

我想用两台笔记本电脑编写一个RMI应用程序,将两个数字相加?我已经将一台笔记本电脑作为服务器,将另一台笔记本电脑作为客户端。当我们要定义从远程接口扩展的接口时,应在客户端或服务器端在哪台计算机上定义此接口?请帮忙。

我使用一台机器制作了一个RMI应用程序,但效果很好。我已经在同一包中定义了Interface,但是当我在其他机器上工作时,它不起作用。

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 个答案:

答案 0 :(得分:1)

  

我们应该在哪里定义接口客户端或服务器端?

简单:您需要在双方两侧都有界面。

客户端知道该接口,并且基本上是它所知道的“唯一的东西”:有一些接口定义了客户端代码可以使用的行为(方法)。

服务器知道该接口并实现

该接口是(概念上)“链接”客户端和服务器的基本内容。他们俩都知道有一些接口AdditionI。客户会需要它

  • 首先确定支持该接口的服务
  • 找到这样的服务后,客户端就会知道如何调用相应的添加方法

另一方面,服务器使用该接口将其实现注册为服务,然后客户端可以调用。

因此,您在源代码中基本上有三个不同部分:

  • 通用:包含该AdditionI接口
  • client :识别并稍后使用该添加服务所需的其他代码
  • 服务器:用于实现和注册服务的附加代码

请注意:异常java.lang.ClassNotFoundException确实很基本。它告诉您运行某些代码的JVM找不到某些类。

换句话说:您的类路径设置已被破坏。只需研究该异常即可(您可以找到有关此类基本内容的无尽文档,例如,参见here)。很有可能,归结为:确保某些.class文件位于类路径中……您需要的位置。第一部分已经告诉您哪些课程需要去哪里!