创建第一个rmi应用
//创建远程接口
package hello;
import java.util.Date;
import java.rmi.*;
public interface HelloService extends Remote{
public String echo(String msg) throws RemoteException;
public Date getTime() throws RemoteException;
}
//创建远程类
package hello;
import java.util.Date;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class HelloServiceImpl extends UnicastRemoteObject implements HelloService{
private String name;
public HelloServiceImpl(String name)throws RemoteException{
this.name=name;
}
public String echo(String msg)throws RemoteException{
System.out.println(name+":调用echo()方法");
return "echo:"+msg +" from "+name;
}
public Date getTime()throws RemoteException{
System.out.println(name+":调用getTime()方法");
return new Date();
}
}
//SimpleServer.java
package hello;
import java.rmi.*;
import javax.naming.*;
public class SimpleServer{
public static void main( String args[] ){
try{
HelloService service1 = new HelloServiceImpl("service1");
HelloService service2 = new HelloServiceImpl("service2");
Context namingContext=new InitialContext();
namingContext.rebind( "rmi:HelloService1", service1 );
namingContext.rebind( "rmi:HelloService2", service2 );
/*
namingContext.rebind( "rmi://localhost:8000/HelloService1", service1 );
namingContext.rebind( "rmi://localhost:8000/HelloService1", service2 );
*/
System.out.println( "服务器注册了两个HelloService对象" );
}catch(Exception e){
e.printStackTrace();
}
}
}
//SimpleClient.java
package hello;
import java.rmi.*;
import javax.naming.*;
public class SimpleClient{
public static void showRemoteObjects(Context namingContext)throws Exception{
NamingEnumeration<NameClassPair> e=namingContext.list("rmi:");
while(e.hasMore())
System.out.println(e.next().getName());
}
public static void main( String args[] ){
String url="rmi://localhost/";
try{
System.setProperty("java.security.policy",SimpleClient.class.getResource("client.policy").toString());
System.setSecurityManager(new RMISecurityManager());
Context namingContext=new InitialContext();
HelloService service1=(HelloService)namingContext.lookup(url+"HelloService1");
HelloService service2=(HelloService)namingContext.lookup(url+"HelloService2");
Class stubClass=service1.getClass();
System.out.println("service1是"+stubClass.getName()+"的实例");
Class[] interfaces=stubClass.getInterfaces();
for(int i=0;i<interfaces.length;i++)
System.out.println("存根类实现了"+interfaces[i].getName());
System.out.println(service1.echo("hello"));
System.out.println(service1.getTime());
System.out.println(service2.echo("hello"));
System.out.println(service2.getTime());
showRemoteObjects(namingContext);
}catch( Exception e){
e.printStackTrace();
}
}
}

浙公网安备 33010602011771号