这里分三步来讲,讲的比较繁琐.也是希望不会的人能尽可能看得懂.会的肯定不会看.OK,开始.
第一部分:服务器(生产者) 需要定义一个远程接口,以及实现该接口的类.
1.公共接口.
package com.pan.rmi.interf;import java.rmi.Remote;import java.rmi.RemoteException;/** * Created by pan on 2016/10/4. */public interface ServiceRemote extends Remote { //远程需要用到的方法 String doSomething() throws RemoteException;}
2.服务端实现接口(远程调用的类)
package com.pan.rmi.impl;import com.pan.rmi.interf.ServiceRemote;import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;/** * Created by pan on 2016/10/4. */public class ServiceImple extends UnicastRemoteObject implements ServiceRemote { /** * 初始化抛出异常 * @throws RemoteException * @since JDK1.1 */ public ServiceImple() throws RemoteException { } @Override public String doSomething() throws RemoteException { System.out.println("Service: A method is called !"); return "Service doSomething ."; }}
3.启动服务端
package com.pan.rmi;import com.pan.rmi.impl.ServiceImple;import java.rmi.Naming;import java.rmi.registry.LocateRegistry;/** * Created by pan on 2016/10/4. */public class Main { public static void main(String[] args) { try { ServiceImple service = new ServiceImple(); //注册方法一// Registry registry = LocateRegistry.createRegistry(9889) ;// registry.rebind("myRemote", service); //注册方法二 LocateRegistry.createRegistry(6600); Naming.rebind("rmi://127.0.0.1:6600/myRemote", service); System.out.println("服务器启动成功!"); } catch (Exception e) { e.printStackTrace(); } }}
第二步:(将接口打包到客户端程序,可以用jar本地包,也可以使用maven本地仓库.)
第三步:(客户端代码调用服务端的方法)
package com.pan.rmi.client;import com.pan.rmi.interf.ServiceRemote;import java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException;/** * Created by pan on 2016/10/4. */public class ClientImpl { public static void main(String[] args) { try { //获取远程服务,这里注意一下端口必须跟服务端设置的一致 ServiceRemote remote = (ServiceRemote) Naming.lookup("rmi://127.0.0.1:6600/myRemote"); //调用远程方法 String s = remote.doSomething(); //输出 System.out.println("客户端接受消息:" + s); } catch (NotBoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } }}
测试结果:
1.客户端
客户端接受消息:Service doSomething .Process finished with exit code 0
2.服务端
服务器启动成功!Service: A method is called !
题外:
RMI是Java内置的一种比较简单的远程调用方式,类是的还有apache的http远程调用.一般用于分布式服务器框架的proxy层,java作为一门高级语言.目前来说socket编程都比较的繁琐,更相对于底层通信(例如tcp/ip协议算法更是...),所以,一般来说都是使用成熟的框架去实现我们的需求.