---
title: "Java RMI 例子 和一些常见问题"
author: "jwu"
date: "2012-11-25T20:37:10Z"
tags: []
categories: ["编程语言"]
slug: "java-rmi"
draft: false
lastmod: "2012-11-25T20:44:51Z"
id: 1734839
url: "https://jwu.iteye.com/blog/1734839"
---

```

```

看到设计模式代理模式时，有个RMI的例子，虽然概念上比较简单，但是自己动手写个例子验证一下。 

依然是经典的 hello world，呵呵。

首先是一个客户端和服务端都需要的接口。

```
import java.rmi.*;

public interface MyRemote extends Remote {
String sayHello() throws RemoteException;
}
```

然后是一个接口的实现类。

 

```
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.LocateRegistry;

public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {

	public String sayHello() {
		return "Server says, 'Hey, Connected!'";
	}
	
	public MyRemoteImpl() throws RemoteException {}
	
	public static void main(String[] args) {
		try {
			LocateRegistry.createRegistry(9998);
			
			MyRemote service = new MyRemoteImpl();
			Naming.rebind("RemoteHello", service);
			System.out.println(service + " successfully bound to RemoteHello");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	
	}
}
```

 

最后是一个客户端调用类。

 

 

```
import java.rmi.*;

public class Client {
	public static void main(String[] args) {
		new Client().go();
	}
	
	public void go() {
		try {
			MyRemote service = (MyRemote) Naming.lookup("rmi://192.168.1.107:9998/RemoteHello");
			String s = service.sayHello();
			
			System.out.println(s);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
```

   
总共就这3个类。

编译：

进入java文件所在目录：

C:\\Users\\Administrator\\Desktop\\rmiExample&gt;javac \*.java

目录大概这个样子：

Client.class  
Client.java  
MyRemote.class  
MyRemote.java  
MyRemoteImpl.class  
MyRemoteImpl.java

再使用rmic生成stub和skeleton类，注意加上-v1.1，不然不会生成skel类。

C:\\Users\\Administrator\\Desktop\\rmiExample&gt;rmic **-v1.1** MyRemoteImpl

生成如下2个文件  
MyRemoteImpl\_Skel.class  
MyRemoteImpl\_Stub.class

把如下类拷到另一台电脑上运行服务器端，也要有Java环境。

MyRemote.class  
MyRemoteImpl.class  
MyRemoteImpl\_Skel.class  
MyRemoteImpl\_Stub.class

本机留着当作客户端机器，只保留如下3个文件，其余全部删掉。  
Client.class  
MyRemote.class  
MyRemoteImpl\_Stub.class

在服务器端电脑运行  
java MyRemoteImpl

这一步如果注释掉MyRemoteImpl类的这一行，

 

```
// LocateRegistry.createRegistry(9998);
```

需要先开一个命令终端运行

rmiregistry 9998

再运行  
java MyRemoteImpl

最后，见证测试结果的时候到了，在本机（作为客户端机器）运行  
java Client  
如果出现打印的  
Server says, 'Hey, Connected. Ready to use.'

表示运行成功。而且本地没有MyRemoteImpl类，可以肯定这个结果是服务器机器上返回的结果。