- package org.itrun.remote;
- import java.rmi.Remote;
- import java.rmi.RemoteException;
- /**
- * 远程接口
- * @author jiangzhen
- *
- */
- public interface TestInterfactRemote extends Remote{
- public String add(String a,String b) throws RemoteException;
- public String add() throws RemoteException;
- }
- package org.itrun.remote;
- import java.rmi.RemoteException;
- import java.rmi.server.UnicastRemoteObject;
- /**
- * 接口的实现
- * @author jiangzhen
- *
- */
- public class TestInterfaceRemoteImpl extends UnicastRemoteObject implements
- TestInterfactRemote {
- public TestInterfaceRemoteImpl() throws RemoteException {
- super();
- }
- public String add(String a, String b) throws RemoteException {
- return a+b;
- }
- public String add() throws RemoteException {
- return "Hello Word";
- }
- }
- package org.itrun.server;
- import java.rmi.Naming;
- import org.itrun.remote.TestInterfaceRemoteImpl;
- import org.itrun.remote.TestInterfactRemote;
- /**
- * 服务器端
- * @author jiangzhen
- *
- */
- public class Server{
- public Server() {
- try {
- TestInterfactRemote testInterfactRemote = new TestInterfaceRemoteImpl();
- Naming.rebind("rmi://10.0.0.123/server", testInterfactRemote);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String args[]) {
- new Server();
- }
- }
- package org.itrun.client;
- import java.rmi.Naming;
- import org.itrun.remote.TestInterfactRemote;
- /**
- * 客户端程序
- * @author jiangzhen
- *
- */
- public class Client {
- public static void main(String args[]) {
- try {
- TestInterfactRemote testInterfactRemote = (TestInterfactRemote) Naming
- .lookup("rmi://10.0.0.123/server");
- System.out.println(testInterfactRemote.add("rmi a ", "rmib"));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
程序完成后
运行RMI系统
现在我们建立了所有运行这个简单RMI系统所需的文件,现在我们终于可以运行这个RMI系统啦!来享受吧。
我们是在命令控制台下运行这个系统的,你必须开启三个控制台窗口,一个运行服务器,一个运行客户端,还有一个运行RMIRegistry。
首先运行注册程序RMIRegistry,你必须在包含你刚写的类的那么目录下运行这个注册程序。
>rmiregistry(linux) start rmiregistry(windows)
运行程序首先需要修改下RMI的安全策略策略文件在 JDK 目录下的jre/lib/security/java.policy 的最后面加上下面这句话
grant{
permission java.security.AllPermission "","";
};
这条命令表示允许任何人作任何事情,
修改完后运行命令 rmiregistry ,然后就不用管他了
然后运行 server 端的代码 运行后也不用管他了
java org.itrun.server.Server
最后运行 client 端代码
java org.itrun.server.Client
运行结果 rmi a rmib