RMI(Remote Method invocation,远程方法访问)

在做的项目中发现了一句:factory.setServiceUrl("rmi://"+url+":"+port+"/ipsvc"); 都说学习java只要学会如何调用底层方法就行,但说是这么说。

咱们还是要了解下底层东东,才能写出大师级别的代码。

出于什么,我百度了下RMI,操,不百度不知道。rmi听起来很厉害的样子,远程方法调用。

何为远程方法调用:跨平台、跨操作系统、跨虚拟机。

简单点就是,你在河东写了个方法,我在河西就能访问到,确实不错。

主文:

rmi程序编写步骤:

  1. 远程接口,要实现Remote接口、
  2. 远程接口实现,实现远程接口同时还要集成UnicastRemoteObject
  3. 远程服务类,绑定端口、绑定对象
  4. 远程访问客户类

开始写程序(没有在IDE上写,错误之处,见谅)

 1 远程接口:必须集成Remote接口
 2 public interface IMessage extends Remote{
 3     public Person getPerson() throws RemoteException;
 4 }
 5 //待传递对象,因此要实现序列化
 6 public class Person implements Serializable{
 7    private int age;
 8    private String name;
 9    
10    public Person(){
11        
12     }
13 
14     public Person(){
15         this.age = age;
16         this.name = name;
17     }
18 }
19 
20 远程接口实现:要集成UnicastRemoteObject类
21 public class MessageImpl extends UnicastRemoteObject implements Rmote{
22     public MessageImpl() throws RemoteException{
23          
24     }
25 
26     public Person getPerson() throws RemoteException{
27           return new Person(22,"**");
28     }
29 }
30 
31 远程接口服务:
32 public class server{
33      public static void main(String agrs[]){
34           if(System.getSercurity() == null){
35                 System.setSecurty(new RmiSercurtyManage());
36            }
37 
38            LocateRegistry.createRegistry(9999);  //绑定服务端口
39 
40            IMessage m = new MessageImpl();
41            Naming.bing("rmi://loacalhost:9999/person",m);
42            System.out.println("remote method is startting.......");
43      }
44 }
45 
46 client:
47 pubic class Client{
48    public static void main(String args[]){
49           if(System.getSercurity() == null){
50                 System.setSecurty(new RmiSercurtyManage());
51            }
52 
53         IMessage m = (IMessage)Naming.lookup("rmi://loacalhost:9999/person");
54          Person p = m.getPerson();
55          System.out.println("" + p.getName());
56    }
57 }

写是能写出来,但有什么用呢?
我在一个项目中建立server和client包,这样是可以访问的。

但是我写两个项目,一个用户server、一个用于client,就会报access denied (java.net.SocketPermission 127.0.0.1:1099 connect,resolve)

这是远程方法访问,我通过Naming.lookup("----");获取的对象,是在远程,是从远程传递过来的。那么我需要调用远程接口的方法,我还必须得到远程的接口。

如果远程接口中定义的方法获取的是对象,就是说,我在本地调用方法获取的是远程的对象。

在本地访问远程方法时:

需要远程接口,

需要远程接口中返回的对象,

需要远程接口绑定的端口,和url

原文地址:https://www.cnblogs.com/lh-V/p/3459117.html