我正在创建我的第一个非常简单的RMI客户端-服务器应用程序。

这是代码:

接口(interface)“ICommunication”

package itu.exercies.RMI.server;

    import java.rmi.Remote;
    import java.rmi.RemoteException;

public interface ICommunication extends Remote
{
    public String doCommunicate(String name) throws RemoteException;

}

接口(interface)实现“CommunicationImpl”:
package itu.exercies.RMI.server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class CommunicationImpl extends UnicastRemoteObject implements ICommunication {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public CommunicationImpl() throws RemoteException {
        super();

    }

    @Override
    public String doCommunicate(String name) throws RemoteException {

        return "Hello this is server , whats up " +name+ " ?!\n";
    }

}

这是服务器“CommunicationServer”的主要类别:
package itu.exercies.RMI.server;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;


public class CommunicationServer {
    /**
     * @param args
     * @throws RemoteException
     * @throws MalformedURLException
     */
    public static void main(String[] args) throws RemoteException, MalformedURLException {
        CommunicationImpl imp = new CommunicationImpl();
        Naming.rebind("CommunicationImpl", imp);
        System.out.println("Server started...");
        System.out.println("Object successfully registered. It is bound to the name 'CommunicationImpl'.");

    }

}

这是我的客户“CommunicationClient”:
package itu.exercies.RMI.client;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import itu.exercies.RMI.server.CommunicationImpl;

public class CommunicationClient {
    public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {

        String url = new String("rmi://localhost/CommunicationImpl");
        CommunicationImpl comm = (CommunicationImpl)Naming.lookup(url);
        String reply = comm.doCommunicate("Wiktor");
        System.out.println(reply);


    }

}

现在,当我尝试运行它时:
  • 我使用终端
  • 导航到项目的bin目录
  • 我从那里运行rmiregistry
  • 我从新的“终端”窗口运行CommunicationServer(它会打印出消息,因此似乎可以正常工作)
  • 我打开第三个终端窗口,当我尝试运行CommunicationClient时,它将引发异常。



  • 到目前为止,我试图通过使用rmic创建一个'CommunicationImpl'对象的存根来修复它,但是现在不是'$ Proxy0',该错误涉及到'CommunicationImpl_Stub':



    目前,我还不知道要寻找错误。有人可以给我任何建议吗?

    最佳答案

    代替

    CommunicationImpl comm = (CommunicationImpl) Naming.lookup(url);
    


    ICommunication comm = (ICommunication) Naming.lookup(url);
    
    CommunicationImplICommunication的服务器实现。客户既不知道也不关心实现,仅关心接口(interface)。

    08-16 12:57