一、构建服务端
1.服务端目录结构
2.定义服务接口
package rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Warehouse extends Remote
{
double getPrice(String description) throws RemoteException;
}
3.服务实现
package rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Map;
public class WarehouseImpl extends UnicastRemoteObject implements Warehouse
{
private static final long serialVersionUID = 1L;
private Map<String,Double> prices;
protected WarehouseImpl() throws RemoteException
{
prices = new HashMap<String,Double>();
prices.put("mate7",3700.00);
}
public double getPrice(String description) throws RemoteException
{
Double price = prices.get(description);
return price == null? 0 : price;
}
}
4.发布服务
package rmi;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import javax.naming.NamingException;
public class WarehouseServer
{
public static void main(String[] args) throws RemoteException, NamingException, MalformedURLException, AlreadyBoundException
{
System.out.println("Constructing server implementation");
WarehouseImpl centralWarehouse = new WarehouseImpl();
System.out.println("Binding server implementation to registry");
LocateRegistry.createRegistry(1099);
Naming.bind("rmi://localhost:1099/central_warehoues",centralWarehouse);
System.out.println("Waiting for invocations from clients ...");
}
}
运行此类,进行发布
Constructing server implementation
Binding server implementation to registry
Waiting for invocations from clients ...
二、编写客户端程序
1.客户端目录结构
2.定义共有的服务接口,与服务端的Warehouse一模一样
3.连接服务端进行测试
package rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import javax.naming.NamingException;
public class WarehouseClient
{
public static void main(String[] args) throws NamingException, RemoteException, MalformedURLException, NotBoundException
{
System.out.println("RMI registry binding:");
String url = "rmi://localhost:1099/central_warehoues";
Warehouse centralWarehouse = (Warehouse) Naming.lookup(url);
String descr = "mate7";
double price = centralWarehouse.getPrice(descr);
System.out.println(descr + ":" + price);
}
}
运行此类,输出结果
RMI registry binding:
mate7:3700.0