RMI简单示例

1、接口定义

package com.neohope.rmi.test;

import java.rmi.Remote;
import java.rmi.RemoteException;

/**
 * Created by Hansen
 */
public interface ITest extends Remote {
    /**
     * 返回“Hi XXX"字符串,必须声明抛出RemoteException异常
     * @return 返回“Hi XXX"字符串
     * @throws java.rmi.RemoteException
     */
    public String sayHiTo(String user) throws RemoteException;

    /**
     * 加法,必须声明抛出RemoteException异常
     * @param a
     * @parma b
     * @return a+b
     * @throws java.rmi.RemoteException
     */
    public int add(int a, int b) throws RemoteException;
}

2、服务端实现

package com.neohope.rmi.test;

import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

/**
 * Created by Hansen
 */
public class TestServer implements ITest, Serializable {

    /**
     * 构造函数,必须声明抛出RemoteException异常
     *
     * @throws RemoteException
     */
    public TestServer() throws RemoteException {
    }

    /**
     * 返回“Hi XXX"字符串
     * @return 返回“Hi XXX"字符串
     * @throws java.rmi.RemoteException
     */
    @Override
    public String sayHiTo(String user) throws RemoteException {
        return "Hi " + user;
    }

    /**
     * 加法
     * @param a
     * @parma b
     * @return a+b
     * @throws java.rmi.RemoteException
     */
    @Override
    public int add(int a, int b) throws RemoteException {
        return a+b;
    }

    public static void main(String[] args) throws IOException, AlreadyBoundException {
        //创建一个远程对象
        ITest server = new TestServer();
        //注册端口
        LocateRegistry.createRegistry(1234);
        //绑定对象
        Naming.bind("rmi://localhost:1234/RemoteTest", server);

        System.in.read();
    }
}

3、客户端实现

package com.neohope.rmi.test;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

/**
 * Created by Hansen
 */
public class TestClient {
    public static void main(String args[]) throws RemoteException, NotBoundException, MalformedURLException {
        //查找服务,并调用方法
        ITest rservice = (ITest) Naming.lookup("rmi://localhost:1234/RemoteTest");
        System.out.println(rservice.sayHiTo("neohope"));
        System.out.println(rservice.add(1,2));
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*