rmi程序创建步骤

来源:互联网 发布:苹果mac装双系统多少钱 编辑:程序博客网 时间:2024/06/10 19:30

  在 Java 语言中,如果一个对象符合以下两个条件,则将其标识为远程的:第一,该对象扩展了

java.rmi.server.UnicastRemoteObject 类;第二,该对象的所有方法引起 RemoteException 错误。几乎所有从

RemoteException 继承的异常都转换为 System.Runtime.Remoting.RemotingException 错误。如果您的应用程序以不同的方

式处理特定的 RemotingException 子类,那么,您必须对这些子类进行手动调整。

1、首先在server端需要一个接口,继承自java.rmi.Remote
package rmi;
import java.rmi.Remote;
import javabean.Person;

public interface Rem extends Remote{
public Person getPerson(Person person)throws java.rmi.RemoteException;
}

2、其次实现这个接口并继承java.rmi.server.UnicastRemoteObject
package rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import javabean.Person;

public class RemImpl extends UnicastRemoteObject implements Rem{

 protected RemImpl() throws RemoteException {
  
 }
 public Person getPerson(Person person) throws RemoteException {
 person.setName("tom");
  return person;
 }
}

3、接着注册服务,绑定端口
package rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

public class Server {
 public static void main(String[] args) throws RemoteException, MalformedURLException {
//  LocateRegistry.createRegistry(8080);  //注册端口
  RemImpl rem=new RemImpl();
  //接着注册服务,绑定端口
  Naming.rebind("rmi://127.0.0.1:8080/Rem",rem);
  System.out.println("注册完毕");
  
 }
}
4、编写类
package javabean;

import java.io.Serializable;
//Serializable:标识性接口
//1.可以在网络中传输
//2.可以写入本地磁盘

public class Person implements Serializable{
private int id;
private String name;
public int getId() {
 return id;
}
public void setId(int id) {
 this.id = id;
}
public String getName() {
 return name;
}
public void setName(String name) {
 this.name = name;
 }  }

5、然后写客户端
package rmi;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import javabean.Person;

public class Client {
 public static void main(String[] args) throws MalformedURLException, RemoteException,

NotBoundException {
  Rem rem=(Rem) Naming.lookup("rmi://127.0.0.1:8080/Rem");
  javabean.Person p=new Person();
  p.setId(1001);
  Person person=rem.getPerson(p);
  System.out.println(person.getId()+":"+person.getName());
 }
}
运行即可。