普通方法实现——远程方法调用RMI代码演示

Posted 戒急静心

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了普通方法实现——远程方法调用RMI代码演示相关的知识,希望对你有一定的参考价值。

1、spring_RMI01_server服务端

1 package com.wisezone.service;
2 
3 import java.rmi.Remote;
4 import java.rmi.RemoteException;
5 
6 public interface IHelloService extends Remote {
7     
8     public String sayHello(String msg) throws RemoteException;
9 }
 1 package com.wisezone.service.impl;
 2 
 3 import java.rmi.RemoteException;
 4 import java.rmi.server.UnicastRemoteObject;
 5 
 6 import com.wisezone.service.IHelloService;
 7 
 8 public class HelloServiceImpl extends UnicastRemoteObject implements IHelloService{
 9 
10     /**
11      * 
12      */
13     private static final long serialVersionUID = -4174742054186163053L;
14 
15     public HelloServiceImpl() throws RemoteException {
16         
17     }
18 
19     @Override
20     public String sayHello(String msg) throws RemoteException {
21         
22         System.out.println("服务端接受消息:"+msg);
23         return "hello,"+msg;
24     }
25 
26 }
 1 package com.wisezone.test;
 2 
 3 import java.net.MalformedURLException;
 4 import java.rmi.AlreadyBoundException;
 5 import java.rmi.Naming;
 6 import java.rmi.RemoteException;
 7 import java.rmi.registry.LocateRegistry;
 8 
 9 import com.wisezone.service.impl.HelloServiceImpl;
10 
11 /**
12  * 发布顺序:先发布服务端,再发布客户端
13  * @author 王东海
14  * @2017年5月1日
15  */
16 public class Publish {
17     
18     public static void main(String[] args) throws RemoteException, MalformedURLException, AlreadyBoundException {
19         
20         //设置端口
21         LocateRegistry.createRegistry(8888);
22         Naming.bind("rmi://127.0.0.1:8888/hello", new HelloServiceImpl());
23         System.out.println("发布成功。。。");
24     }
25 }

2、spring_RMI01_client客户端

1 package com.wisezone.service;
2 
3 import java.rmi.Remote;
4 import java.rmi.RemoteException;
5 
6 public interface IHelloService extends Remote {
7     
8     public String sayHello(String msg) throws RemoteException;
9 }
 1 package com.wisezone.test;
 2 
 3 import java.net.MalformedURLException;
 4 import java.rmi.Naming;
 5 import java.rmi.NotBoundException;
 6 import java.rmi.RemoteException;
 7 
 8 import com.wisezone.service.IHelloService;
 9 
10 public class Test {
11     
12     public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
13         IHelloService helloService = (IHelloService) Naming.lookup("rmi://127.0.0.1:8888/hello");
14         System.out.println("客户端接受消息:"+helloService.sayHello("This is 5月1号劳动节"));
15     }
16 }

发布顺序:先发布服务端,再发布客户端

结果:

 

以上是关于普通方法实现——远程方法调用RMI代码演示的主要内容,如果未能解决你的问题,请参考以下文章

RMI(Remote Method Invocation ) 概念恢复

Java RMI地址解析问题

RMI远程方法调用

Java的RMI远程方法调用实现和应用

远程方法调用(RMI)原理与示例

远程方法调用(RMI)原理与示例 (转)