Rmi的简单使用

1、Rmi服务端

1.1 写一个接口继承Remote接口

public interface ISayHello extends Remote {

    public void sayHello() throws RemoteException;

    public String sayHello(String msg) throws RemoteException;

}

1.2 写该接口的实现,该实现类要继承UnicastRemoteObject 类,然后加上该类构造方法

public class SayHelloImpl extends UnicastRemoteObject implements ISayHello {

    private SayHelloImpl() throws RemoteException {
    }

    private static class Inner{

        private static SayHelloImpl INSTANCE;

        private static SayHelloImpl getInstance() throws RemoteException{
            if(INSTANCE==null){
                INSTANCE = new SayHelloImpl();
            }
            return INSTANCE;
        }
    }

    public static SayHelloImpl getInstance() throws RemoteException{
        return Inner.getInstance();
    }

    @Override
    public void sayHello() throws RemoteException {

        System.out.println("excute sayHello()-> hello world");

    }

    @Override
    public String sayHello(String msg) throws RemoteException {

        System.out.println("excute sayHello(String msg)-> hello "+ msg);
        return "hello "+msg;
    }
}

1.3 注册服务

public class MyRmiServer  {

    public static void main(String[] args) {

        try {
            ISayHello sayHello = SayHelloImpl.getInstance();
            LocateRegistry.createRegistry(9993);
            Naming.bind("rmi://localhost:9993/sayHello",sayHello);
            System.out.println("MyRmiServer start success ....");

        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (AlreadyBoundException e) {
            e.printStackTrace();
        }


    }

}

2 Rmi客户端

public class MyRmiClient {

    public static void main(String[] args) {

        try {

            ISayHello sayHello = (ISayHello)Naming.lookup("rmi://localhost:9993/sayHello");
            sayHello.sayHello();
            String msg = sayHello.sayHello("MyRmiClient");
            System.out.println("msg = " + msg);


        } catch (NotBoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值