JAVA-RMI基础

Java RMI 基础

RMI(Remote Method Invocation). 他是一种机制, 能够让某个java虚拟机上的对象调用另一个java虚拟机中的对象上的方法。可以用此方法调用任何对象必须实现该接口。来源自百度百科

测试代码

  • 接口 IHello.java

    1
    2
    3
    4
    5
    6
    7
    import java.rmi.Remote;
    import java.rmi.RemoteException;

    // 继承 Remote
    public interface IHello extends Remote {
    String sayHelloToSomeBody(String someBodyName) throws RemoteException;
    }
  • 实现接口 HelloImpl.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;

    public class HelloImpl extends UnicastRemoteObject implements IHello {


    protected HelloImpl() throws RemoteException {
    super();
    }

    public String sayHelloToSomeBody(String someBodyName) throws RuntimeException {
    System.out.println("Connected Successfully!");
    System.out.println("您好, " + someBodyName + "!");
    return "您好, " + someBodyName + "!";
    }
    }
  • 服务端代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    import java.net.MalformedURLException;
    import java.rmi.AlreadyBoundException;
    import java.rmi.Naming;
    import java.rmi.RemoteException;
    import java.rmi.registry.LocateRegistry;

    public class HelloServer {

    public static void main(String[] args) {
    try {
    IHello iHello = new HelloImpl();
    // 本地主机上的远程对象注册表 Registry 实例, 注册端口
    LocateRegistry.createRegistry(8888);
    // 设置系统属性 java.rmi.server.hostname 的值为 127.0.0.1
    System.setProperty("java.rmi.server.hostname", "127.0.0.1");
    // 把远程对象注册到 RMI 注册服务器上, 并命名为 IHello
    Naming.bind("rmi://localhost:8888/IHello", iHello);
    System.out.println("INFO: Remote Object IHello bind successfully..");
    }catch (RemoteException e) {
    System.out.println("创建对象发生异常");
    e.printStackTrace();
    }catch (AlreadyBoundException e){
    System.out.println("已经绑定了对象");
    e.printStackTrace();
    }catch (MalformedURLException e) {
    System.out.println("发生URL异常");
    e.printStackTrace();
    }
    }
    }
  • 客户端代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    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 {
    // 创建远程对象
    IHello iHello = (IHello) Naming.lookup("rmi://127.0.0.1:8888/IHello");
    // 进行调用
    System.out.println(iHello.sayHelloToSomeBody("Loid"));
    }catch (NotBoundException e) {
    e.printStackTrace();
    }catch (MalformedURLException e) {
    e.printStackTrace();
    }catch (RemoteException e) {
    e.printStackTrace();
    }
    }
    }