简单的javaRIM 实现

来源:互联网 发布:mac finder添加 编辑:程序博客网 时间:2024/05/16 01:53

代理模式中的远程代理简单实现:


制作远程的接口

package proxy;import java.rmi.Remote;import java.rmi.RemoteException;/* * 定义远程接口 */public interface MyRemote extends Remote{        public String sayHello() throws RemoteException;}

制作远程的实现 并将服务注册到 RMI register 中
pakage proxyimport java.rmi.Naming;import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{        // UnicastRemoteobject 实现了某些"远程功能"。其构造方法 抛出了 RemoteException 异常    protected MyRemoteImpl() throws RemoteException {            }    @Override    public String sayHello() throws RemoteException {        return "Server says 'Hey'";    }    public static void main(String arg[]){        System.out.println("服务启动!");        try{            MyRemote service = new MyRemoteImpl();            //将指定名称重新绑定到一个新的远程对象            Naming.rebind("RemoteHello", service);                    }catch (Exception e){                    }    }}

打开一个终端 对 MyRemoteImpl 进行javac 编译

用 rmic 编译 MyRemoteImpl 将生成MyRemoteImpl_Stub.class 文件。这是远程代理的 辅助对象。

重新打开终端  打开启用 rmiregistry (使用 Naming.rebind()注册必须运行

运行 MyRemoteImpl (java MyRemoteImpl) 开启远程服务)




package proxy;import java.rmi.Naming;public class MyRemoteClient {public static void main(String arg[]){new MyRemoteClient().go();}public void go(){try {MyRemote service = (MyRemote) Naming.lookup("rmi://127.0.0.1/RemoteHello");String s = service.sayHello();System.out.println(s);} catch (Exception e) {e.printStackTrace();}}}


运行客户端

注意:在Myeclipse ,Eclipse 不支持 rmic 的编译,必须下载插件 并安装


原创粉丝点击