RMI 应用

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Date;

/**
 * Description:<br>
 * 1.创建远程接口,继承java.rmi.Remote接口
 * 2.创建远程类,实现远程接口
 * 3.创建服务器端程序:负责在rmiregistry注册表中注册远程对象
 * 4.创建客户端程序:负责定位远程对象,并调用远程对象的方法
 * @author JOJO
 * @version 0.1
 */
public interface HelloService extends Remote
{
 
    public String echo (String msg) throws RemoteException;

    public Date getTime () throws RemoteException;
}

 

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;

public class HelloServiceImpl extends UnicastRemoteObject implements HelloService
{

    private String            name;

    protected HelloServiceImpl(String name) throws RemoteException
    {
        this.name = name;

        /*
         * UnicastRemoteObject的构造方法会调用自身的exportObject(Remote obj,int port)。
         * 该方法负责把参数obj指定的对象导出为远程对象,使它具有相应的存根, 并使它能够监听远程客户端的方法调用请求。
         * 参数port指定监听的端口。 如果远程对象已经继承其他类,那么可以在构造方法中调用UnicastRemoteObject的
         * 静态方法exportObject(Remote obj,int port)。
         */
        // UnicastRemoteObject.exportObject(this, 0);
    }

    public String echo (String msg) throws RemoteException
    {
        System.out.println(name + ":调用echo()方法。");
        return "echo:" + msg + " from " + name;
    }

    public Date getTime () throws RemoteException
    {
        System.out.println(name + "调用getTime()方法。");
        return new Date();
    }

}

 

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * Description:<br>
 * @author JOJO
 * @version 0.1
 */
public class SimpleServer
{
    public static void main (String[] args)
    {
        try
        {
            HelloService service1 = new HelloServiceImpl("service1");
            HelloService service2 = new HelloServiceImpl("service2");
            //创建并导出接受指定 port 请求的本地主机上的 Registry 实例。
            Registry registry = LocateRegistry.createRegistry(1099);
            registry.rebind("HelloService1", service1);
            registry.rebind("HelloService2", service2);
            System.out.println("服务器注册了两个HelloService对象。");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

 

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * Description:<br>
 * 
 * @author JOJO
 * @version 0.1
 */
public class SimpleClient
{

    public static void main (String[] args)
    {
        try
        {
            // 返回指定的 host 和 port 上对远程对象 Registry 的引用。
            Registry registry = LocateRegistry.getRegistry("127.0.0.1", 1099);
            HelloService service1 = (HelloService) registry.lookup("HelloService1");
            HelloService service2 = (HelloService) registry.lookup("HelloService2");

            System.out.println(service1.echo("hello"));
            System.out.println(service2.getTime());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}

 

你可能感兴趣的:(java,应用服务器)