1、先创建一个工程



2、创建新模块





3、再创建一个客户端




4、先在服务端创建一个接口
先创建接口,创建实现类。
IHelloService接口
public interface IHelloService extends Remote {// 1、定义一个sayHello方法public String sayHello(User user) throws RemoteException;}
IHelloServiceImpl实现类
public class IHelloServiceImpl extends UnicastRemoteObject implements IHelloService {// 手动实现父类的构造方法protected IHelloServiceImpl() throws RemoteException {super();}// 我们自定义的sayHello,将来要进行网络传输,这个User是要经过远程调用的// user需要序列化,则User类中需要实现序列化接口@Overridepublic String sayHello(User user) throws RemoteException {System.out.println("this is server, say hello to "+user.getUsername());return "success";}}
user类
public class User implements Serializable {private String username;private int age;public User() {}public User(String username, int age) {this.username = username;this.age = age;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}
RMIServer启动类
public class RMIServer {public static void main(String[] args) throws RemoteException, AlreadyBoundException, MalformedURLException {// 1、创建HelloService 实例IHelloService service = new IHelloServiceImpl();// 2、获取注册表LocateRegistry.createRegistry(8888);// 3、对象的绑定// bind 方法的参数1: rmi://ip地址:端口/服务名 参数2: 绑定的对象Naming.bind("//127.0.0.1:8888/myrmiserver",service);}}
5、在客户端创建一个启动类
RMIClient客户端
public class RMIClient {// 通过这个主方法去调用远程服务public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException {//1、从注册表中获取远程对象,强转// 因为在服务端绑定的时候根据127.0.0.1....这个协议绑定的,所以现在也得通过协议取出// 查询到的肯定是接口对象,所以这里可以强转为接口// lookup这个对象其实是一个代理对象IHelloService lookup = (IHelloService) Naming.lookup("//127.0.0.1:8888/myrmiserver");//2、准备参数User user = new User("haha", 18);//3、调用远程方法sayHelloString message = lookup.sayHello(user);System.out.println(message);}}
6、启动两个启动类
客户端、服务端完成了远程调用。

