RMI之所以使用的范围受限制主要有两方面原因,其一:必须要是java,平台的异构性受到限制;其二:穿越防火墙不方便。这里主要谈谈RMI如何通过固定分配端口来穿越防火墙。 RMI穿越防火墙不方便主要是因为除了RMI服务注册的端口(默认1099)外,与RMI的通讯还需要另外的端口来传送数据,而另外的端口是随机分配的,所以要想RMI的客户能通过防火墙来与RMI服务通讯,则需要能让随机分配的端口固定下来,具体做法如下:
public class RunServer {
public static void main(String[] args) throws UnknownHostException {
String ipAdd = InetAddress.getLocalHost().getHostAddress();
String port = "9889";
String serverName = "doc2PdfService";
System.out.println("地址:[" + ipAdd + "]");
System.out.println("端口:[" + port + "]");
System.out.println("服务名称:[" + serverName + "]");
try {
System.out.println("开始启动服务");
System.setProperty("java.rmi.server.hostname", ipAdd);
//此为随机分配的端口,固定为8500
IDoc2PdfService sms = new Doc2PdfServiceImpl(8500);
LocateRegistry.createRegistry(Integer.valueOf(port).intValue());
Naming.rebind("rmi://" + ipAdd + ":" + port + "/" + serverName, sms);
System.out.println("服务 " + serverName + " 启动成功!请勿关闭!");
} catch (RemoteException e) {
System.out.println("创建远程对象发生异常,服务启动失败!");
System.out.println(e.getMessage());
} catch (MalformedURLException e) {
System.out.println("发生URL畸形异常,服务启动失败!");
System.out.println(e.getMessage());
}
}
}
public class Doc2PdfServiceImpl extends UnicastRemoteObject implements IDoc2PdfService {
private static final long serialVersionUID = 516354934025044848L;
private static final String tempFilePath = "D:\\doc2pdf\\file\\";
public Doc2PdfServiceImpl(int port) throws RemoteException {
super(port);
}
}