1.创建远程接口
package com.wilian.rmi.server; import java.rmi.Remote; import java.rmi.RemoteException; public interface HelloWorld extends Remote{//必须继承Remote接口 //必须要抛出RemoteExcepttion的异常,不然启动远程服务时会报错java.rmi.server.ExportException: remote object implements illegal remote interface; String sayHello(String name) throws RemoteException; }
2.创建远程对象
package com.wilian.rmi.server; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class HelloWorldImpl extends UnicastRemoteObject implements HelloWorld { protected HelloWorldImpl() throws RemoteException {} @Override public String sayHello(String name) throws RemoteException { return "Hello "+name; } }
3.创建远程服务器
package com.wilian.rmi.server; import java.rmi.RemoteException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class HelloWorldServer { public static void main(String[] args) { try { HelloWorld hello=new HelloWorldImpl(); Context namingContext=new InitialContext(); //使用本地JNDI注册服务,注册格式为rmi://host//服务名,如果JNDI服务器在与远程服务器在同一机器可省略掉host namingContext.rebind("rmi:HelloWorld", hello); System.out.println("服务器注册了一个HelloWorld对象"); } catch (RemoteException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } } }
4.创建客户端程序
package com.wilian.rmi.client; import java.rmi.RemoteException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import com.wilian.rmi.server.HelloWorld; public class HelloWorldClient { public static void main(String[] args) { String url="rmi://localhost/"; try { Context namingContext = new InitialContext(); //从JNDI服务器上寻找对应的服务 HelloWorld hello = (HelloWorld)namingContext.lookup(url+"HelloWorld"); System.out.println(hello.getClass().getName()); System.out.println(hello.sayHello("wilian")); } catch (NamingException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } } }
5.运行程序
启动JNDI服务:start rmiregistry 如果是用eclipse进行开发必须到工程对应的bin目录下进行启动,否则会报HelloWorld类无法找到
启动服务端
启动客户端
运行截图