分类:
2008-11-18 20:26:24
现在虽然我们很少用到RMI进行编程,但是做为Java一个最早的分布式解决方案,我们还是有了解的必要,从例子开始吧(虽然是几年前的了)!
远程接口RmiHelloRemoteIntfc .java
import java.rmi.*;
public interface RmiHelloRemoteIntfc extends Remote
{
String helloRemoteObj(String client) throws RemoteException;
}
远程接口的实现类RmiHelloRemoteObj.java
import java.rmi.server.*;
import java.rmi.*;
public class RmiHelloRemoteObj extends UnicastRemoteObject implements RmiHelloRemoteIntfc
{
public RmiHelloRemoteObj() throws RemoteException
{
super();
}
public String helloRemoteObj(String client) throws RemoteException
{
return "Hello World"+client;
}
}
服务器类RmiHelloServer.java
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import sun.applet.*;
import java.rmi.registry.LocateRegistry;
public class RmiHelloServer
{
public RmiHelloServer()
{
}
public static void main(String[] args)
{
//创建并安装安全管理器
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new RMISecurityManager());
}
try{
//创建远程对象
RmiHelloRemoteObj ttt=new RmiHelloRemoteObj();
//启动注册表
LocateRegistry.createRegistry(2222);
//奖名称绑定到对象
Naming.rebind("//Fangm:2222/helloObj",ttt);
System.out.println("RMI服务器正在运行。。。。。。");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
服务器端的权限文件RmiHelloServer.policy
grant codeBase
"file:/e:/download/rmitest/"
{
permission java.net.SocketPermission
"*:1000-9999","accept,connect,listen,resolve";
};
现在就看看Client端是如何连接服务器和进行远程方法的调用的吧
import java.rmi.*;
import java.rmi.server.*;
public class RmiHelloClient
{
public RmiHelloClient()
{
}
public static void main(String[] args)
{
//创建并安装安全管理器
if(System.getSecurityManager()==null)
{
System.setSecurityManager(new RMISecurityManager());
}
try{
RmiHelloRemoteIntfc c1=(RmiHelloRemoteIntfc)Naming.lookup("rmi://Fangm:2222/helloObj");
System.out.println(c1.helloRemoteObj("Everyone"));
}
catch(Exception e)
{
e.printStackTrace();
}
System.exit(0);
}
}
Client端的权限文件RmiHelloClient.policy
grant codeBase
"file:/e:/download/rmitest/"
{
permission java.net.SocketPermission
"*:1000-9999","accept,connect,listen,resolve";
};
好了,一个最简单的RMI例子就安无了,对了还少了最重要的一步,那就是编译和运行呢?我们就来了个Bat或Cmd的批处理来进行吧,
看看RmiHello.bat吧
javac RmiHelloRemoteIntfc.java
javac RmiHelloRemoteObj.java
rmic RmiHelloRemoteObj
javac RmiHelloServer.java
javac RmiHelloClient.java
echo 在另一个窗口启动服务器,请稍后。。。
start java -Djava.security.policy=RmiHelloServer.policy RmiHelloServer
echo 运行客户程序。。。
java -Djava.security.policy=RmiHelloClient.policy RmiHelloClient