Java RMI远程调用

具体代码:

首先定义接口:
public interface IService extends Remote{
/**
* 声明服务端必须提供的服务
* 注意:这里要抛出RemoteException异常
*/
String service(String str)throws RemoteException;
}


定义实现类:
@SuppressWarnings("serial")
/**
* 必须集成UnicastRemoteObject类用于导出远程对象和获得与远程对象通信的存根
*/
public class ServiceImpl extends UnicastRemoteObject implements IService{
private String name;
public ServiceImpl(String name) throws RemoteException{
this.name=name;
}

@Override
public String service(String str) {
return name+">>"+str;
}

}


定义注册类:
public class Service {
public static void main(String[] args) {
try {
Registry registry=LocateRegistry.createRegistry(2000);
IService service02=new ServiceImpl("service02");
//将命名绑定到对象,即想命名空间注册已经实例化的远程服务对象
registry.bind("service02", service02);
} catch (AccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AlreadyBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("向服务端注册了一个远程对象....");

}
}




然后将IService接口导出,放在另一个工程下面。并编写客户端类Client。

public class Client {
public static void main(String[] args) {
try {
String url="rmi://localhost:2000/";
Context naming=new InitialContext();
//检索指定的对象,即找到服务器端相应的服务对象存根
IService service02=(IService)naming.lookup(url+"service02");
Class stubClass=service02.getClass();
System.out.println("service02 是 "+stubClass.getName() +"的实例");

Class[] interfaces=stubClass.getInterfaces();
for(Class c:interfaces){
System.out.println("存根类实现了:"+c.getName()+" 接口");
}
String s= service02.service("测试");
System.out.println(s);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}




运行顺序:
1.0先启动java的远程注册程序D:\Program Files\Java\jre\bin\rmiregistry.exe ;
2.0其次运行Service类,注册服务;
3.0然后运行Client类;



打印结果:
service02 是 $Proxy0的实例
存根类实现了:java.rmi.Remote 接口
存根类实现了:inf.IService 接口
service02>>测试












你可能感兴趣的:(java,rmi)