Java RMI示例

给出Java RMI(Remote Method Invocation,远程方法调用)的示例。

示例

  • HelloInterface.java
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* Created by lbd on 2017/11/12.
*/
public interface HelloInterface extends Remote {
public String helloWorld() throws RemoteException;
public String sayHello(String name) throws RemoteException;
}
  • HelloImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* Created by lbd on 2017/11/12.
*/
public class HelloImpl extends UnicastRemoteObject implements HelloInterface {
public HelloImpl() throws RemoteException {}
public String helloWorld() throws RemoteException {
return "hello world!";
}
public String sayHello(String name) throws RemoteException {
return "hello " + name + "!";
}
}
  • HelloServer.java
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
/**
* Created by lbd on 2017/11/12.
*/
public class HelloServer {
public static void main(String[] args) {
try {
HelloInterface hello = new HelloImpl();
LocateRegistry.createRegistry(6789);
Naming.bind("rmi://localhost:6789/rHello", hello);
System.out.println("远程HelloInterface对象绑定成功,可以被调用");
} catch (RemoteException e) {
System.out.println("创建远程对象发生异常!");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("url异常!");
e.printStackTrace();
} catch (AlreadyBoundException e) {
System.out.println("重复绑定异常!");
e.printStackTrace();
}
}
}
  • HelloClient.java
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
/**
* Created by lbd on 2017/11/12.
*/
public class HelloClient {
public static void main(String[] args) {
try {
HelloInterface rHello = (HelloInterface) Naming.lookup("rmi://localhost:6789/rHello");
System.out.println(rHello.helloWorld());
System.out.println(rHello.sayHello("lbd"));
} catch (RemoteException | MalformedURLException | NotBoundException e) {
e.printStackTrace();
}
}
}

运行

程序运行顺序如下:

  1. 运行HelloServer
  2. 运行HelloClient

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD's Blog All Rights Reserved.

访客数 : | 访问量 :