RMI(远程方法调用)用于java程序之间的远程方法调用,下面是一个简单例子。
一、创建服务端项目
1. 创建RmiInterface接口,代码实现如下:
public interface RmiInterface extends Remote {
/**
*
* @param name
* @return
* @throws RemoteException
*/
public String doService(String name) throws RemoteException;
}
2. 创建RmiInterface模板接口的实现类ServiceImpl,代码实现如下:
public class ServiceImpl extends UnicastRemoteObject implements RmiInterface{
public ServiceImpl() throws RemoteException {
super();
}
@Override
public String doService(String hostName) throws RemoteException {
System.out.println("client name is: " + hostName);
return "服务连接正常!";
}
}
3. 创建Server服务端类,代码实现如下:
public class Server {
public static void main(String[] args) {
try {
ServiceImpl serviceImpl = new ServiceImpl();
LocateRegistry.createRegistry(8888);
Naming.bind("rmi://192.168.1.6:8888/RMIService", serviceImpl);
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
System.out.println("RMI 服务正常启动!");
}
}
二、创建客户端项目:
- 将刚才创建的RmiInterface的复制过来,也可将RmiInterface的class文件拷贝过来,但必须保持一致。
- 创建Client客户端类,代码实现如下:
public class Client {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
RmiInterface service = (RmiInterface) Naming.lookup("rmi://192.168.1.6:8888/RMIService");
System.out.println(service.doService(address.getHostName()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}