Java-Rmi案例,远程过程调用

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值