RmiClient
package com.lv.rmi;
import java.rmi.Naming;
import java.util.List;
/**
* Created by lvyanghui
* 2018/11/1 16:23
*/
public class RmiClient {
public static void main(String[] args) throws Exception{
StudentService studentService = (StudentService)Naming.lookup("rmi://localhost:5008/studentService");
List<Student> list = studentService.getList();
for (Student s : list) {
System.out.println("姓名:"+s.getName()+",年龄:"+s.getAge());
}
}
}
RmiServer
package com.lv.rmi;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
/**
* Created by lvyanghui
* 2018/11/1 16:19
*/
public class RmiServer {
public static void main(String[] args) throws Exception{
StudentService studentService = new StudentServiceImpl();
LocateRegistry.createRegistry(5008);
Naming.rebind("rmi://localhost:5008/studentService",studentService);
System.out.println("服务已启动");
}
}
Student
package com.lv.rmi;
import java.io.Serializable;
/**
* Created by lvyanghui
* 2018/11/1 16:13
*/
public class Student implements Serializable{
private static final long serialVersionUID = -3111492742628447261L;
private String name;
private int age;
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;
}
}
StudentService
package com.lv.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
/**
* Created by lvyanghui
* 2018/11/1 16:15
*/
public interface StudentService extends Remote{
List<Student> getList() throws RemoteException;
}
StudentServiceImpl
package com.lv.rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lvyanghui
* 2018/11/1 16:16
*/
public class StudentServiceImpl extends UnicastRemoteObject implements StudentService{
protected StudentServiceImpl() throws RemoteException {
}
public List<Student> getList() throws RemoteException {
List<Student> list = new ArrayList<Student>();
Student s1=new Student();
s1.setName("张三");
s1.setAge(15);
Student s2=new Student();
s2.setName("李四");
s2.setAge(20);
list.add(s1);
list.add(s2);
return list;
}
}