1.
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface HelloRMI extends Remote
{
String printHello(String msg) throws RemoteException;
}
2.
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloRMImpl extends UnicastRemoteObject implements HelloRMI{
public HelloRMImpl() throws RemoteException {
super();
}
private static final long serialVersionUID = 1L;
@Override
public String printHello(String msg) throws RemoteException {
System.out.println(msg);
return msg;
}
public static void main(String[] args)
{
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new RMISecurityManager());
}
try
{
HelloRMImpl obj=new HelloRMImpl();
Naming.bind("//localhost:2008/HelloServer", obj);
System.out.println("OK to bound the RMIServer");
}
catch(Exception e)
{
}
}
}
3.
import java.rmi.Naming;
public class HelloClient {
/**
* @param args
*/
public static void main(String[] args) {
String msg="Hello World!";
HelloRMI obj=null;
try
{
obj=(HelloRMI)Naming.lookup("//localhost:2008/HelloServer");
System.out.println(" in RMI Client.the Msg is:"+obj.printHello(msg));
}
catch(Exception e)
{
}
}
}
4.配置运行RMI代码
A.在D盘下面建立一个rmi的目录,把上面三个.java文件放入其中
B.进入命令窗口,在D:/rmi的目录下,通过javac *.java命令,编译上述三个.java文件,编译通过后,会在这个目录里面出现对应的.class文件
C.通过rmic HelloRMImpl命令。为HelloRMImpl生成一个“桩”执行完毕会在目录下面出现HelloRMImpl_Stub.class
D.成功生成“桩”文件之后,可以通过start rmiregistry 2008命令,开启RMI服务注册程序,只有开启这个程序,才能运行RMI的服务器和客户端程序
E.开启完成后,会弹出一个新的命令窗口,别关闭继续在本窗口下执行如下的命令
java -Djava.security.policy=policy HelloRMImpl
在执行之前必须在目录下增加一个policy的描述文件
grant {
// Allow everything for now
permission java.security.AllPermission;
};
说明为RMI服务器开启一切权限
运行完毕会在服务器段看到如下的信息
OK to bound the RMI Servive
F.新开启一个DOS命令窗口,进入目录 运行java HelloClient开启客户端代码,则会在服务器端输出
Hello World!
而在RMI客户端输出:
in RMI Client ,the message is :Hello World!