peersim学习-循环驱动:如何写协议(1)
循环驱动模式的协议只要继承CDProtocol就OK了,peersim会在每一个cycle里在每个节点上执行nextCycle()方法; 为了获取邻接信息,必须配置IdleProtocol( implements Protocol, Linkable),这个协议是peersim.core中的核心代码。
Linkable linkable = (Linkable) node.getProtocol(linkableID)获取IdleProtocol对象(IdleProtocol实现于linkable接口)。 上面是peersim实现cdsim的类,对于循环驱动协议只需要使用者实现CDProtocol接口就OK了: 1)CDSimulator,中是主要的cdsim实现的过程; 2)CDState,设置和获取当前的cycle即时间; 3)DeamonProtocol,这不是一个真正的protocol,提供一个可以在任何时候运行control类的方法,设置step控制运行时间。 4)FullNextCycle,每个cycle时,控制协议运行(运行协议的nextCycle方法)和更新CDState的状态。 5)NextCycle,与FullNextCycle作用一样,由private static final String PAR_NOMAIN = "simulation.nodefaultcycle";配置使用NextCycle还是FullNextCycle。NextCycle的灵活性要比FullNextCycle好,为精通的使用者使用。 6)Shuffle,顾名思义就是打乱节点在数组中的位置。 下图是CDSIM的主要过程,protocol类封装成FullNextCycle和配置的control类一起运行。 01publicclassAverageFunctionextendsSingleValueHolderimplementsCDProtocol{ 02/**03*Createsanew{@linkexample.aggregation.AverageFunction}protocol 04*instance. 05* 06*@paramprefix 07*thecomponentprefixdeclaredintheconfigurationfile. 08*/ 09publicAverageFunction(Stringprefix){ 10super(prefix); 11} 12 13/** 14*Usinganunderlying{@linkLinkable}protocolchosesaneighborand 15*performsavariancereductionstep. 16* 17*@paramnode 18*thenodeonwhichthiscomponentisrun. 19*@paramprotocolID 20*theidofthisprotocolintheprotocolarray. 21*/ 22publicvoidnextCycle(Nodenode,intprotocolID){ 23intlinkableID=FastConfig.getLinkable(protocolID); 24Linkablelinkable=(Linkable)node.getProtocol(linkableID); 25if(linkable.degree()>0){ 26Nodepeer=linkable.getNeighbor(CommonState.r.nextInt(linkable 27.degree())); 28 29//Failurehandling 30if(!peer.isUp()) 31return; 32 33AverageFunctionneighbor=(AverageFunction)peer 34.getProtocol(protocolID); 35doublemean=(this.value+neighbor.value)/2; 36this.value=mean; 37neighbor.value=mean; 38} 39} 40 41} 看看源码中的这个示例,这个协议实现用gossip获取整个网络中节点平均值,每一个cycle,每个节点和自己的邻居求平局值。nextCycle方法是每个cycle在每个节点中运行的。以上就是主要的CDSIM的主要过程和编程方法。 |