rmi使用

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;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值