版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26641781/article/details/83147119
- 定义一个远程接口
public interface IService extends Remote{
public String queryName(String no) throws RemoteException;
}
- 实现远程的接口
public class ServiceImpl extends UnicastRemoteObject implements IService {
private static final long serialVersionUID = 1L;
protected ServiceImpl() throws RemoteException {
}
@Override
public String queryName(String no) throws RemoteException {
//方法的具体实现
System.out.println("hello "+ no);
return String.valueOf(System.currentTimeMillis());
}
}
- RMI服务器端程序
public class Server {
public static void main(String[] args) {
//注册管理器
Registry registry = null;
try {
//创建一个服务注册管理器
registry = LocateRegistry.createRegistry(8088);
System.out.println("registry");
} catch (RemoteException e) {
e.printStackTrace();
}
try {
//创建一个服务
ServiceImpl service = new ServiceImpl();
//将服务绑定命名
registry.rebind("vince",service);
System.out.println("bind server");
} catch (Exception e) {
e.printStackTrace();
}
}
}
- RMI客户端调用程序
public class Client {
public static void main(String[] args) {
//注册管理器
Registry registry = null;
try {
//获取服务注册管理器
registry = LocateRegistry.getRegistry("localhost",8088);
//列出所有注册的服务
String[] list = registry.list();
for (String s : list){
System.out.println(s);
}
} catch (RemoteException e) {
e.printStackTrace();
}
try {
//根据命名获取服务
IService service = (IService) registry.lookup("vince");
//调用远程方法
String result = service.queryName("jack");
//输出调用结果
System.out.println("result from remote : "+result);
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}