服务器端业务接口继承自Remote
public interface Biz extends Remote {
public String aloha() throws RemoteException;
}
public class BizImpl extends UnicastRemoteObject implements Biz {
private static final long serialVersionUID = -8559392326593037120L;
public BizImpl() throws RemoteException {
super();
}
@Override
public String aloha() throws RemoteException {
return "Aloha Baby.";
}
}
服务器注册远程实现名称
public class Server {
public Server() {
try {
Biz bis = new BizImpl();
// style-1
Registry registry = LocateRegistry.createRegistry(RMIParameter.PORT);
registry.rebind(RMIParameter.NAME, bis); // replace existing binding name
// style-2
//java.rmi.Naming.rebind(RMIParameter.NAME, bis); // replace existing binding name
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
new Server();
}
}
style-2 需要指定一个Policy文件或者运行rmiregistry
java -Djava.security.policy=folder_x/rmi/policy_file creative.fire.rmi.Server
Policy文件的内容为:
grant{
permission java.net.SocketPermission "localhost:9527", "connect, resolve";
};
运行rmiregistry是修改 JDK 目录下的jre/lib/security/java.policy
rmiregistry(linux)
start rmiregistry(windows)
允许任何人(targets)作任何事情(actions):
grant{
permission java.security.AllPermission "","";
};
OR
grant {
permission java.security.AllPermission;
};
客户端打桩调用
public class Client {
public static void main(String args[]) {
try {
Biz bis = (Biz) Naming.lookup(RMIPREFIX + PORT + NAME);
System.out.println(bis.aloha());
} catch (Exception e) {
e.printStackTrace();
}
}
}