參考:java
RMI是相似RPC的一種遠程方法調用協議,比RPC類型的WebService更簡單,也能夠跨進程訪問this
先來建立一個model或者javaBean,注意,該類必須實現序列化Serializable .net
public class Person implements Serializable { private int id; private String name; private int age; public void setId(int id) { this.id = id; } public int getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } }
調用接口
code
//此爲遠程對象調用的接口,必須繼承Remote類 public interface PersonService extends Remote { public List<Person> GetList() throws RemoteException; }
實現接口,注意必須繼承UnicastRemoteObject 對象
public class PersonServiceImpl extends UnicastRemoteObject implements PersonService { public PersonServiceImpl() throws RemoteException { super(); // TODO Auto-generated constructor stub } @Override public List<Person> GetList() throws RemoteException { // TODO Auto-generated method stub System.out.println("Get Person Start!"); List<Person> personList=new LinkedList<Person>(); Person person1=new Person(); person1.setAge(25); person1.setId(0); person1.setName("Leslie"); personList.add(person1); Person person2=new Person(); person2.setAge(25); person2.setId(1); person2.setName("Rose"); personList.add(person2); return personList; } }
Server端blog
public class RMIServer{ public static void main(String[] args) { try { PersonService personService=new PersonServiceImpl(); //註冊通信端口 LocateRegistry.createRegistry(6600); //註冊通信路徑 Naming.rebind("rmi://127.0.0.1:6600/PersonService", personService); System.out.println("Service Start!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
客戶端繼承
public class RMIClient { public static void main(String[] args){ try{ //調用遠程對象,注意RMI路徑與接口必須與服務器配置一致 PersonService personService=(PersonService)Naming.lookup("rmi://127.0.0.1:6600/PersonService"); List<Person> personList=personService.GetList(); for(Person person:personList) { System.out.println("ID:"+person.getId()+" Age:"+person.getAge()+" Name:"+person.getName()); } }catch(Exception ex){ ex.printStackTrace(); } } }