首页 > 编程 > Java > 正文

Java.RMI远程方法调用

2019-11-08 19:26:33
字体:
来源:转载
供稿:网友
RMI(Remote Method Invocation,远程方法调用)是java进行调用远程对象的一种技术,基于Java远程消息交换协议JRMP(Java Remote Messaging PRotocol)进行通信。形象来说,就是你把服务端的对象写好、绑定到某个端口,就可以在客户端访问这个对象的方法了客户端需要知道的有ip和端口,以及绑定名客户端有怎么知道对象有什么方法呢?这里有Remote对象来标记,即实现了Remote对象的方法才可以被远程调用,这是客户端和服务端都需要知道的内容。这个Remote可以被实现为一个接口,用来进行通信。

HelloRMI

这里实现一个很简单的案例,即服务端的对象是一个只会说一句话的鹦鹉,即Hello,客户端可以通过RMI听到这个鹦鹉说话。当然怎么可能是音频,只是println罢了。

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.

搞定!


千变万化的服务端方法,使得远程客户端可以实现各种各样的功能目前打算练习一个传输文件的小例子作为本次的实验作业了,一个范例另有一篇详细的概念介绍,传送门
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表