扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
在本页阅读全文(共7页)
请注意FileInterface的以下特征:
public,这样客户机才能加载实现远程接口 的远程对象。 
Remote接口,以满足使该对象成为远程对象的 要求。 
java.rmi.RemoteException。 实现远程接口
下一步是实现接口FileInterface。实现的范例见代码范例2。 请注意,除了实现FileInterface之外,还把FileImpl 类扩展为UnicastRemoteObject。这表示FileImpl类 将用于创建一个单独的、不可复制的远程对象,它使用RMI缺省的基于TCP的传送 通道进行通讯。 
代码范例2: FileImpl.java
import java.io.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class FileImpl extends UnicastRemoteObject
implements FileInterface {private String name;
public FileImpl(String s) throws RemoteException{super();
name = s;
}
public byte[] downloadFile(String fileName){try {File file = new File(fileName);
byte buffer[] = new byte[(int)file.length()];
BufferedInputStream input = new
BufferedInputStream(new FileInputStream(fileName));
input.read(buffer,0,buffer.length);
input.close();
return(buffer);
} catch(Exception e){System.out.println("FileImpl: "+e.getMessage());e.printStackTrace();
return(null);
}
}
}
开发服务器
第三个步骤是开发服务器。服务器需要做三件事:
FileImpl)的一个实例 
代码范例 3: FileServer.java
import java.io.*;
import java.rmi.*;
public class FileServer {public static void main(String argv[]) {if(System.getSecurityManager() == null) {System.setSecurityManager(new RMISecurityManager());
}
try {FileInterface fi = new FileImpl("FileServer");Naming.rebind("//127.0.0.1/FileServer", fi);} catch(Exception e) {System.out.println("FileServer: "+e.getMessage());e.printStackTrace();
}
}
}
语句Naming.rebind("//127.0.0.1/FileServer", fi)假定RMI 注册表在缺省的端口号1099上运行。但是,如果RMI注册表在其他端口号上运行, 就必须在这一句中指定端口号。例如,如果RMI注册表在端口4500
上运行,那么 这一句就变成:
Naming.rebind("//127.0.0.1:4500/FileServer", fi) 
另外,在这里要着重指出,我们假定rmi注册表和服务器是在同一台电脑上运 行。如果不是这样,只需修改rebind方法中的地址即可。
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。