通过Java Rmi 的远程方法调用返回一个对象列表,代码如下:
?
1、Server服务接口
class="java">import java.rmi.Remote; import java.rmi.RemoteException; import java.util.List; //须继承Romote类 public interface IStuService extends Remote { public List<Student> getStudet() throws RemoteException; }
?
2、Server服务接口实现类
import java.rmi.RemoteException; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; //须继承UnicastRemoteObject类 同时要重写构造方法 由于父类的构造方法抛异常了 public class StuServiceImpl extends UnicastRemoteObject implements IStuService { public StuServiceImpl() throws RemoteException { super(); } public StuServiceImpl(int i, RMIClientSocketFactory rmiclientsocketfactory, RMIServerSocketFactory rmiserversocketfactory) throws RemoteException { super(i, rmiclientsocketfactory, rmiserversocketfactory); } public StuServiceImpl(int i) throws RemoteException { super(i); } @Override public List<Student> getStudet() throws RemoteException { List<Student> list = new ArrayList<Student>(); Student s1 = new Student(); s1.setId(1); s1.setName("xxx"); Student s2 = new Student(); s2.setId(2); s2.setName("yyy"); list.add(s1); list.add(s2); return list; } }
?
3、Server服务发布类
import java.rmi.Naming; import java.rmi.registry.LocateRegistry; public class RmiServer { public static void main(String[] args) { try { IStuService ss = new StuServiceImpl(); // 注册一个通讯端口 LocateRegistry.createRegistry(6666); // 注册一个通讯路径 Naming.rebind("rmi://127.0.0.1:6666/service", ss); System.out.println("Service Start!"); } catch (Exception e) { e.printStackTrace(); } } }
?
4、Entity实体类(注意:实体类必须实现Serializable接口)
public class Student implements java.io.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、Client客户端
import java.rmi.Naming; import java.util.List; public class Client { public static void main(String[] args) { try { // 此处不能强制转换为接口的实现类 IStuService ss = (IStuService) Naming .lookup("rmi://127.0.0.1:6666/service"); List<Student> list = ss.getStudet(); for (Student stu : list) { System.out.println(stu.getId() + "--------" + stu.getName()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
?
?