发送端向接收端发送资源,前提是,必须知道接收端地址,以及请求资源片段。
ServerClient 只是仅负责资源发送。那么发送之前还需与接收端进行沟通。
1. 资源拥有者
资源拥有者有三个职责:
- 向资源注册中心,注册资源,作为RMI客户端。
- 与接收端进行会话,作为RMI服务器。
- 向接收端发送资源,作为RMI客户端。
1.1 会话服务器
与发送端沟通获取接收端地址与资源请求。
private RMIServer rourecerHolderServer;
private Node me;
public ResourceHolder(String rmiConfigPath) throws IOException {
this.rourecerHolderServer = new RMIServer();
//配置RMI服务器
InitializationWork.loadConfig(rmiConfigPath, rourecerHolderServer);
PropertiesParse pp = new PropertiesParse();
//设置本地网络节点
this.me = new Node();
me.setIp(new String(InetAddress.getLocalHost().getAddress()));
me.setPort(Integer.parseInt(pp.value("serverPort");
}
1.1.1 接收端会话处理
- 接收端会话
public interface IResourceHolderAction {
/**
*
* @param resourceId 资源ID
* @param address 接收端地址
* @param sectionList 资源请求列表
*/
void dealResourceRequest(int resourceId, ResourceReceiverAddress address,
List<SectionHander> sectionList);
}
- 会话处理
public class ResourceHolder implements IResourceHolderAction {
@Override
public void dealResourceRequest(int resourceId, ResourceReceiverAddress address, List<SectionHander> sectionList) {
try {
//获取资源本地资源信息,这里使用SpringIOC
ResourceInfo resourceInfo = BeanFactory.getBean(ResourceHolderResourcePool.class)
.getResourceInfo(resourceId);
//开启发送客户端
SenderClient senderClient = new SenderClient(address.getIp(), address.getPort(),
resourceInfo, sectionList);
senderClient.send();
} catch (IOException e) {
e.printStackTrace();
}
}
}
本地资源信息获取,用Spring。RMI动态代理对象,是克隆对象,并非原对象,克隆对象无法访问本地资源。故需要将本地资源单例化。
1.2客户端
向资源注册中心注册资源
private IResourceRegistryCenterAction action;
public ResourceHolder(String rmiConfigPath) throws IOException {
RMIClient rmiClient = new RMIClient();
rmiClient.setIp(pp.value("registryIp"));
rmiClient.setPort(Integer.parseInt(pp.value("registryPort")));
//获取注册中心服务代理对象,可与注册中心发送服务请求。
this.action = (IResourceRegistryCenterAction) new ClientProxy(rmiClient)
.getProxy(IResourceRegistryCenterAction.class);
}
1.2.1 注册资源
public ResourceHolder registerResource(int resourceId) {
this.action.register(resourceId, me);
return this;
}
1.3 其他操作
public void startUp() {
rourecerHolderServer.startUp();
}
public void addListener(IListener listener) {
this.rourecerHolderServer.addListener(listener);
}
public void shutDown() {
this.rourecerHolderServer.shutDown();
}
public void addResource(int resourceId, ResourceInfo resourceInfo) {
this.holderResourcePool.addResource(resourceId, resourceInfo);
}
public void setResourceAbsolute(int resourceId, String absoluteRoot) throws Exception {
ResourceInfo resourceInfo = this.holderResourcePool.getResourceInfo(resourceId);
resourceInfo.setAbsoluteRoot(absoluteRoot);
}