1.编写Remote接口
Remote 接口用于标识其方法可以从非本地虚拟机上调用的接口。通过这样一个接口,客户端就知道服务端的对象有哪些方法可以调用,也可以直接通过接口来实现方法的调用import java.rmi.Remote;import java.rmi.RemoteException;public interface IParrot extends Remote{ //远程访问标记接口,只有在Remote接口中标记的方法猜可以远程调用 public String say() throws RemoteException;}2.编写服务端的鹦鹉对象
除了实现IParrot接口外,还必须扩展实现UnicastRemoteObject类,才能成为一只真正的远程鹦鹉import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;public class ParrotImpl extends UnicastRemoteObject implements hello{ private static final long serialVersionUID = 1L; public ParrotImpl () throws RemoteException{ super(); } public String say() throws RemoteException { return "Hello,I'm a parrot."; } }3.编写服务端程序server
来我们把这只鹦鹉绑定到一个端口上这里使用的IP地址是127.0.0.1即本地,只要修改成其他IP即可import java.rmi.Naming;import java.rmi.registry.LocateRegistry;public class server { public static void main(String[] args){ try { IParrot p = new ParrotImpl(); LocateRegistry.createRegistry(2048);//绑定端口 Naming.bind("rmi://127.0.0.1:2048/parrot", p);//绑定对象 System.out.println("ParrotServer启动成功"); } catch (Exception e) { e.printStackTrace(); } }}4.编写客户端程序client
server本身作为一个进程运行这里的client是另外一个进程虽然是本地,但只要这两个进行运行在两台电脑上,同时保证ip和port对应,既可以实现真正的远程调用import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; public class client { public static void main(String[] args) { try { //获取远程对象,并利用IParrot接口来进行方法调用 IParrot p = (IParrot)Naming.lookup("rmi://127.0.0.1:2048/parrot"); System.out.println(p.say()); } catch (MalformedURLException e) { System.out.println("url格式异常"); } catch (RemoteException e) { System.out.println("创建对象异常"); e.printStackTrace(); } catch (NotBoundException e) { System.out.println("对象未绑定"); } } }5.运行
这一步就比较简单了,为了编译运行两个进程,个人建议在win上配置好java后进入cmd操作用linux的话直接开几个终端就好了以win下的cmd操作为例
首先进入代码所在的目录编译代码>javac *.java运行server>java serverParrotServer启动成功另启一个cmd来运行client>java clientHello,I'm a parrot.搞定!
新闻热点
疑难解答