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 一定要一致.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值