Java-Rmi案例,远程过程调用
服务器端
Animal接口定义:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Animal extends Remote{
public String whoami()throws RemoteException;
}
Animal具体实现Dog:
public class Dog implements Animal {
public String whoami(){
return "i am a dog";
}
}
服务端暴露接口:
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class RmiServer {
public static void main(String[] args) throws RemoteException, InterruptedException {
Dog dog = new Dog();
Remote Animal = UnicastRemoteObject.exportObject(dog,0);
Registry registry = LocateRegistry.createRegistry(1099);
registry.rebind("dog",Animal);
Thread.sleep(1000000000);
}
}
客户端
客户端接口定义要同服务器端包名所有一致:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Animal extends Remote{
public String whoami()throws RemoteException;
}
客户端调用服务器端结果:
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RmiClient {
public static void main(String[] args) throws RemoteException, NotBoundException {
Registry registry = LocateRegistry.getRegistry(1099);
Animal dog = (Animal)registry.lookup("dog");
System.out.println(dog.whoami());
}
}
结果:
客户端打印结果成功:i am a dog