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

普通方法实现——远程方法调用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代码演示