RMI 的使用方法
java 远程调用:RMI
服务器端:
1.首先定义一个接口:
例:
/**
- 定义接口
- 接口方法:set。get
- @author shinion
/
public interface Service extends Remote
{
public void setMsg(String msg) throws RemoteException;
public String getMsg() throws RemoteException;
}
2.定义一个类,实现接口
/*
- 定义一个类,实现接口
- @author shinion
*/
class MyService extends UnicastRemoteObject implements Service{
private String msg = "";
protected MyService() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
@Override
public void setMsg(String msg) throws RemoteException{
// TODO Auto-generated method stub
this.msg = msg;
}
@Override
public String getMsg() throws RemoteException{
// TODO Auto-generated method stub
return msg;
}
}
3.启动服务,定义一个服务类,主函数中启动服务,5008为端口,可以自定义,只要不冲突即可,127.0.0.1为需要绑定的服务的IP地址,端口后面Service应该是接口,不要写成实现的类
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
LocateRegistry.createRegistry(5008);
Naming.rebind("rmi://127.0.0.1:5008/Service", new MyService());
System.out.println("create service and start");
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
客户端:
1.定义接口,和服务端的接口一样
/**
- 定义接口
- 接口方法:set。get
- @author shinion
*/
public interface Service extends Remote
{
public void setMsg(String msg) throws RemoteException;
public String getMsg() throws RemoteException;
}
2.使用:在需要使用的地方调用Naming.lookup方法即可
Service myService = (Service)Naming.lookup(“rmi://127.0.0.1:5008/Service”);
myService.setMsg(“hello”);
System.out.println(myService.getMsg());