java rmi的一个简单实例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java rmi的一个简单实例相关的知识,希望对你有一定的参考价值。
参考网站 http://www.cnblogs.com/leslies2/archive/2011/05/20/2051844.html
实体类PersonEntity
package net.cs30.rmi; import java.io.Serializable; /** * Created by caochenghua on 2017/4/4. */ public class PersonEntity implements Serializable { private int id; private String name; private int age; 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
服务接口PersonService
package net.cs30.rmi; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.List; /** * Created by caochenghua on 2017/4/4. */ public interface PersonService extends Remote { public List<PersonEntity> GetList() throws RemoteException; }
服务接口实现PersonServiceImpl
package net.cs30.rmi; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.LinkedList; import java.util.List; /** * Created by caochenghua on 2017/4/4. */ public class PersonServiceImpl extends UnicastRemoteObject implements PersonService { protected PersonServiceImpl() throws RemoteException { super(); } @Override public List<PersonEntity> GetList() throws RemoteException { System.out.println("Get Person Start!"); List<PersonEntity> personEntityList=new LinkedList<>(); PersonEntity personEntity=new PersonEntity(); personEntity.setAge(10); personEntity.setId(0); personEntity.setName("cao"); personEntityList.add(personEntity); PersonEntity personEntity2=new PersonEntity(); personEntity2.setAge(10); personEntity2.setId(123); personEntity2.setName("horizon"); personEntityList.add(personEntity2); return personEntityList; } }
服务器端测试代码Program
package net.cs30.rmi; import java.rmi.Naming; import java.rmi.registry.LocateRegistry; /** * Created by caochenghua on 2017/4/4. */ 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){ e.printStackTrace(); } } }
客户端测试代码ProgramClient
package net.cs30.rmi; import java.rmi.Naming; import java.util.List; /** * Created by caochenghua on 2017/4/4. */ public class ProgramClient { public static void main(String[] args) { try { PersonService personService=(PersonService) Naming.lookup("rmi://127.0.0.1:6600/PersonService"); List<PersonEntity> personEntityList=personService.GetList(); for (PersonEntity personEntity:personEntityList){ System.out.println("ID:"+personEntity.getId()+" Age:"+personEntity.getAge()+" Name:"+personEntity.getName()); } }catch (Exception e){ e.printStackTrace(); } } }
运行结果
服务器端输出
客户端输出
以上是关于java rmi的一个简单实例的主要内容,如果未能解决你的问题,请参考以下文章