Java RMI 之牛刀小试

按照wiki说明的例子,照猫画虎实现java rmi 。以下是撸主的具体步骤:

1、声明远程调用的接口,并且自定义接口要继承java.rmi.remote:

public interface RmiServerIntf extends Remote {

	public String getMessage() throws RemoteException;
}
2、远程接口的实现类以及远程服务开启的main主方法:

public class RmiServer extends UnicastRemoteObject implements RmiServerIntf {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4312093539786965438L;

	private static String MESSAGE = "Hello, RMI!";
	/**
	 * @throws RemoteException
	 */
	protected RmiServer() throws RemoteException {
		super(0); // required to avoid the 'rmic' step, see below
	}

	/* (non-Javadoc)
	 */
	public String getMessage() throws RemoteException {
		return MESSAGE;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println("RMI Server started");
		try {
			LocateRegistry.createRegistry(1099);
			System.out.println("java RMI registry created.");
		} catch (RemoteException e) {
			//do nothing, error means registry already exists
            System.out.println("java RMI registry already exists.");
		}
		//Instantiate RmiServer
        RmiServer obj = new RmiServer();
     // Bind this object instance to the name "RmiServer"
        Naming.rebind("//localhost/RmiServer", obj);
        System.out.println("PeerServer bound in registry");
	}

}
3、新建调用远程方法的客户端类:

public class RmiClient {

	public static void main(String[] args) throws Exception {
		RmiServerIntf server = (RmiServerIntf) Naming.lookup("//localhost/RmiServer");
		System.out.println(server.getMessage());
	}
}
OK, 有了远程服务类,开启服务的主函数,还有个调用远程方法的客户端类,接下来的步骤:

1、运行RmiServer的main方法, 控制台显示如下,则正确:



2、然后保持远程服务开启,运行RmiClient类,如果成功调用,那么已经入门rmi。

note that:

1、远程服务的端口默认是1099,所以你调用的时候可以省略端口,直接localhost/<your_service_name>;

2、注册的服务的ip 和 port 与客户端调用的ip port 一定要一致.


发布了77 篇原创文章 · 获赞 2 · 访问量 12万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章