标签:rmi简单案例
RMI即远程方法调用,案例步骤
创建对外接口 继承Remote类
创建其实现类 实现类需继承UnicastRemoteObject类并实现其接口
服务端:注册服务端口,并通过rmi链接进行绑定
1)创建接口对象
2)通过LocalRegistry.createRegisty(port);注册端口服务
3)通过Naming.bing("rmi连接字符串",接口对象);
客户端:查找服务并执行
Naming.lookup("rmi连接串")返回其相应的接口对象;
public interface Talk extends Remote{ public String say() throws RemoteException; }
public class TalkImpl extends UnicastRemoteObject implements Talk{ private static final long serialVersionUID = 1L; /*因为UnicastRemoteObject 类构造方法显示抛出RemoteException 所以此处必须有个空的构造方法并将异常抛出*/ public TalkImpl() throws RemoteException { super(); } @Override public String say() { return "hello"; } }
public class Server { public static void main(String[] args) { try { Talk talk=new TalkImpl(); LocateRegistry.createRegistry(8888); //绑定的URL标准格式为:rmi://host:port/name,其中协议名可以省略 Naming.bind("//localhost:8888/talk", talk); } catch (Exception e) { e.printStackTrace(); } } }
public class Clinet { public static void main(String[] args) { try { Talk talk=(Talk)Naming.lookup("//localhost:8888/talk"); System.out.println(talk.say()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } catch (NotBoundException e) { e.printStackTrace(); } } }
最后先启动 Server端 而后启动 Client端 就会输出 hello
本文出自 “丿依然灬淡漠” 博客,请务必保留此出处http://startrun.blog.51cto.com/10157079/1638030
标签:rmi简单案例
原文地址:http://startrun.blog.51cto.com/10157079/1638030