建立PersonServiceImpl实现远程接口,注意此为远程对象实现类,需要继承UnicastRemoteObject
package rmi.serviceImpl; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.LinkedList; import java.util.List; import rmi.model.PersonEntity; import rmi.service.*; //此为远程对象的实现类,须继承UnicastRemoteObject public class PersonServiceImpl extends UnicastRemoteObject implements PersonService { public PersonServiceImpl() throws RemoteException { super(); // TODO Auto-generated constructor stub } public List<PersonEntity> GetList() throws RemoteException { // TODO Auto-generated method stub System.out.println("Get Person Start!"); List<PersonEntity> personList=new LinkedList<PersonEntity>(); PersonEntity person1=new PersonEntity(); person1.setAge(25); person1.setId(0); person1.setName("Leslie"); personList.add(person1); PersonEntity person2=new PersonEntity(); person2.setAge(25); person2.setId(1); person2.setName("Rose"); personList.add(person2); return personList; } } |
建立服务器端,在服务器端注册RMI通讯端口与通讯路径,然后通讯javac命令编译文件,通过java -server 命令注册服务。以下面代码为例,如果阁下将项目建立于D:\\RMI\RemotingService文件夹上时,则先输入D:\\RMI\RemotingService\src>javac rmi/remotingservice/Program.java获取Program.class(如何阁下使用的MyEclipse等开发工具,可跳过此步,直接在*/bin文件夹中直接调用已经生成的Program.class),然后输入D:\\RMI\RemotingService\src>java rmi/remotingservice/Program启动服务。
package rmi.remotingservice; import java.rmi.Naming; import java.rmi.registry.LocateRegistry; import rmi.service.*; import rmi.serviceImpl.*; public class Program{ 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(); } } } |