⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udpapp.java

📁 一个小型网络仿真器的实现
💻 JAVA
字号:
/*
   JaNetSim  ---  Java Network Simulator
   -------------------------------------

   This software was developed at the Network Research Lab, Faculty of
   Computer Science and Information Technology (FCSIT), University of Malaya.
   This software may be used and distributed freely. FCSIT assumes no responsibility
   whatsoever for its use by other parties, and makes no guarantees, expressed or
   implied, about its quality, reliability, or any other characteristic.

   We would appreciate acknowledgement if the software is used.

   FCSIT ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION AND
   DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING
   FROM THE USE OF THIS SOFTWARE.
*/

package janetsim.component;

import janetsim.*;
import javax.swing.*;

public class UDPApp extends SimComponent implements java.io.Serializable {
  private class UDPCon implements UDPUser,java.io.Serializable {
    Object key=null;
    SimParamIP con_sourceip=null, con_destip=null;
    SimParamInt con_sourceport=null, con_destport=null;
    SimParamInt cn_conattempt=null;
    int cn_cur_trans_size=0; //in bytes
    int cn_con_done=0;
    int cn_num_sent=0;
    int cn_status;

    public void receive_packet(int src_ip,int src_port,SimComponent fromlink,
                                UDPBuffer buf) {
      //ignore all incoming packets...
    }
  }

  private SimParamDouble cn_bit_rate;
  private SimParamInt cn_start_time;
  private SimParamInt cn_packet_size;
  private SimParamDouble cn_trans_size1;
  private SimParamDouble cn_trans_size2;
  private SimParamInt cn_repeat;
  private SimParamInt cn_delay;
  private SimParamInt cn_start_delay;
  private SimParamBool cn_random_size;
  private SimParamBool cn_random_delay;
  private SimParamBool cn_random_target;
  private SimParamBool cn_name_seed;

  private SimParamIP cn_destip;
  private SimParamInt cn_destport;
  private SimParamUDP cn_udp;
  private SimPFInt cn_con_num;
  private SimPFInt cn_cur_con;

  private int cur_showing=0;

  private java.util.Random randgen;

  private java.util.List cons;

//connection status constants
  private static final int CON_NULL = 0;
  private static final int CON_ACTIVE = 1;

  private static final int MY_PROTOCOL = IPPacket.PRO_UDP;

//private events
  private static final int MY_START = SimProvider.EV_PRIVATE + 1;
  private static final int MY_SENDCELL = SimProvider.EV_PRIVATE + 2;

//compInfo IDs
  //SimProvider.CI_TRANSPORT_SEND implemented (forwarded ;)
  //SimProvider.CI_PF_INT implemented


  public UDPApp(String name,String aClass,Sim aSim,int locx,int locy) {
    super(name,aClass,aSim,locx,locy);

    randgen=new java.util.Random();
    cn_create();
  }

  public boolean isConnectable(SimComponent comp) {
    if(!super.isConnectable(comp)) return false;

    if(neighborCount()==0 && comp.getCompClass().equals("Router"))
      return true;
    return false;
  }

  public void copy(SimComponent comp) {
    if(comp instanceof UDPApp) {
      UDPApp theComp=(UDPApp)comp;
      cn_bit_rate.setValue(theComp.cn_bit_rate.getValue());
      cn_start_time.setValue(theComp.cn_start_time.getValue());
      cn_packet_size.setValue(theComp.cn_packet_size.getValue());
      cn_trans_size1.setValue(theComp.cn_trans_size1.getValue());
      cn_trans_size2.setValue(theComp.cn_trans_size2.getValue());
      cn_repeat.setValue(theComp.cn_repeat.getValue());
      cn_delay.setValue(theComp.cn_delay.getValue());
      cn_start_delay.setValue(theComp.cn_start_delay.getValue());
      cn_random_size.setValue(theComp.cn_random_size.getValue());
      cn_random_delay.setValue(theComp.cn_random_delay.getValue());
      cn_random_target.setValue(theComp.cn_random_target.getValue());
      cn_name_seed.setValue(theComp.cn_name_seed.getValue());
      cn_destip.setValue(theComp.cn_destip.getValue());
      cn_destport.setValue(theComp.cn_destport.getValue());
      cn_con_num.setValue(theComp.cn_con_num.getValue());
    }
  }

  public void reset() {
    cn_udp.reset();

    for(int i=0;i<cons.size();i++) {
      UDPCon con=(UDPCon)cons.get(i);
      if(con.con_sourceport.getValue()!=0 && neighborCount()>0) {
        //release port number to host
        Integer [] parms=new Integer[2];
        parms[0]=new Integer(con.con_sourceport.getValue());
        parms[1]=new Integer(MY_PROTOCOL);
        neighbor(0).compInfo(IPRouter.REMOVE_PORT,this,parms);
        con.con_sourceport.setValue(0);
      }
      con.cn_conattempt.setValue(0);
      con.cn_conattempt.update(theSim.now());
      con.cn_con_done=0;
      con.cn_num_sent=0;
      con.cn_status=CON_NULL;
    }
  }

  public void start() {
    if(neighborCount()==0) return; //must not send without a neighbor!

    if(cn_name_seed.getValue()==true)
      randgen.setSeed(getName().hashCode());

    int i;
    for(i=0;i<randgen.nextInt(100);i++) randgen.nextDouble();

    fill_connection();
    for(i=0;i<cn_con_num.getValue();i++) {
      UDPCon con=(UDPCon)cons.get(i);
      con.con_sourceip.setValue(((Integer)neighbor(0).compInfo(IPRouter.GET_IP,this,null)).intValue());
      if(con.con_sourceport.getValue()==0) {
        con.con_sourceport.setValue(((Integer)neighbor(0).compInfo(IPRouter.GET_PORT,this,new Integer(MY_PROTOCOL))).intValue());
      }
      myStart(con);
    }
  }

  public void action(SimEvent e) {
    switch(e.getType()) {
      case MY_START:
      case MY_SENDCELL:
        myStart((UDPCon)e.getParams());
        break;
      case SimProvider.EV_RECEIVE:
        cn_receive(e);
        break;
    }
  }

////compInfo of UDPApp:
////(refer constant definitions near the beginning of the class declaration)
  public Object compInfo(int infoid,SimComponent src,Object paramlist) {
    switch(infoid) {
      case SimProvider.CI_TRANSPORT_SEND:
        if(neighborCount()==0) break;
        return  neighbor(0).compInfo(infoid,src,paramlist);
      case SimProvider.CI_PF_INT:
        SimPFInt pfint=(SimPFInt)paramlist;
        if(pfint==cn_cur_con) {
          show_connection();
        }
        break;
    }
    return null;
  }

///////////////////// private methods ////////////////////////////////

  private void cn_create() {
    cons=new java.util.ArrayList();

    //Initialize the parameters
    long ctick=theSim.now();
    cn_bit_rate=new SimParamDouble("Bit Rate (MBits/s)",this,ctick,false,true,0);
    cn_start_time=new SimParamInt("Start time (usecs)",this,ctick,false,true,0);
    cn_packet_size=new SimParamInt("Packet size (bytes, 18-1472)",this,ctick,false,true,548);
    cn_trans_size1=new SimParamDouble("Transmission size (KByte) (from)",this,ctick,false,true,0);
    cn_trans_size2=new SimParamDouble("Transmission size (KByte) (to)",this,ctick,false,true,0);
    cn_repeat=new SimParamInt("Repeat count (-1=inf)",this,ctick,false,true,0);
    cn_delay=new SimParamInt("Delay between calls (usecs)",this,ctick,false,true,1000000);
    cn_start_delay=new SimParamInt("Starting delay (usecs)",this,ctick,false,true,1000000);
    cn_random_size=new SimParamBool("Random data size",this,ctick,false,true,false);
    cn_random_delay=new SimParamBool("Random delay",this,ctick,false,true,false);
    cn_random_target=new SimParamBool("Random destination",this,ctick,false,true,true);
    cn_name_seed=new SimParamBool("Use name as seed",this,ctick,false,true,false);
    cn_destip=new SimParamIP("Destination IP (non-random)",this,ctick,false,true,0);
    cn_destport=new SimParamInt("Destination port (non-random)",this,ctick,false,true,0);
    cn_udp=new SimParamUDP("UDP",this,ctick);
    cn_con_num=new SimPFInt("Number of source",this,ctick,false,true,1);
    cn_cur_con=new SimPFInt("Show Connection #",this,ctick,false,true,0);

    addParameter(cn_bit_rate);
    addParameter(cn_start_time);
    addParameter(cn_packet_size);
    addParameter(cn_trans_size1);
    addParameter(cn_trans_size2);
    addParameter(cn_repeat);
    addParameter(cn_delay);
    addParameter(cn_start_delay);
    addParameter(cn_random_size);
    addParameter(cn_random_delay);
    addParameter(cn_random_target);
    addParameter(cn_name_seed);
    addParameter(cn_destip);
    addParameter(cn_destport);
    addParameter(cn_udp);
    addParameter(cn_con_num);
    addParameter(cn_cur_con);
  }

  private UDPCon create_connection() {
    UDPCon con=new UDPCon();
    con.con_sourceip=new SimParamIP("Source IP",this,theSim.now(),false,false,0);
    con.con_sourceport=new SimParamInt("Source port",this,theSim.now(),false,false,0);
    con.con_destip=new SimParamIP("Destination IP",this,theSim.now(),false,false,0);
    con.con_destport=new SimParamInt("Destination port",this,theSim.now(),false,false,0);
    con.cn_conattempt=new SimParamInt("Calls attempted",this,theSim.now(),true,false,0);
    con.cn_conattempt.update(theSim.now());
    con.cn_status=CON_NULL;
    return con;
  }

  private void fill_connection() {
    while(cn_con_num.getValue()>cons.size()) {
      cons.add(create_connection());
    }
  }

  private void show_connection() {
    int i;
    UDPCon con;

    if(cn_cur_con.getValue()>cn_con_num.getValue() ||
        cn_cur_con.getValue()<0) {
      cn_cur_con.setValue(0);
    }
    if(cur_showing>0) {
      if(cur_showing!=cn_cur_con.getValue()) {
        con=(UDPCon)cons.get(cur_showing-1);
        java.util.List parms=new java.util.LinkedList();
        parms.add(con.con_sourceip);
        parms.add(con.con_sourceport);
        parms.add(con.con_destip);
        parms.add(con.con_destport);
        parms.add(con.cn_conattempt);
        removeParameters(parms);
        cur_showing=0;
      }
      else return;
    }
    if(cn_cur_con.getValue()==0) return;

    while(cn_cur_con.getValue()>cons.size()) {
      cons.add(create_connection());
    }

    con=(UDPCon)cons.get(cn_cur_con.getValue()-1);
    java.util.List parms=new java.util.LinkedList();
    parms.add(con.con_sourceip);
    parms.add(con.con_sourceport);
    parms.add(con.con_destip);
    parms.add(con.con_destport);
    parms.add(con.cn_conattempt);
    addParameters(parms);
    cur_showing=cn_cur_con.getValue();
  }

  private void myStart(UDPCon con) {
    if(SimClock.USec2Tick(cn_start_time.getValue()) <= theSim.now()) {
      switch(con.cn_status) {
        case CON_NULL:
          if(cn_repeat.getValue()>con.cn_con_done || cn_repeat.getValue()==-1) {
            if(cn_random_target.getValue()) {
              if(!setRandomTarget(con)) return; //bye bye if no targets at all...
            }
            else { //fix target
              if(cn_destip.getValue()!=0 && cn_destport.getValue()!=0) {
                con.con_destip.setValue(cn_destip.getValue());
                con.con_destport.setValue(cn_destport.getValue());
              }
              else return; //bye byte if a proper target is not set
            }
    
            con.cn_conattempt.setValue(con.cn_conattempt.getValue()+1);
            con.cn_conattempt.update(theSim.now());
    
            con.cn_cur_trans_size = getTransSize();
            con.cn_num_sent=0;

            con.key=cn_udp.getUDP().open(con.con_sourceip.getValue(),con.con_sourceport.getValue(),
                                          con.con_destip.getValue(),con.con_destport.getValue(),
                                          con);
            con.cn_status = CON_ACTIVE;

            theSim.enqueue(new SimEvent(MY_SENDCELL,this,this,theSim.now(),con));
          }
          break;

        case CON_ACTIVE:
          if(con.cn_num_sent < con.cn_cur_trans_size) {
            cn_udp.getUDP().send(con.key,new UDPBuffer(cn_packet_size.getValue(),null));

            long interval=SimClock.USec2Tick(cn_packet_size.getValue()*8/cn_bit_rate.getValue());
            theSim.enqueue(new SimEvent(MY_SENDCELL,this,this,theSim.now()+interval,con));
            con.cn_num_sent++;
          }
          else {
            cn_udp.getUDP().close(con.key);
            con.cn_con_done++;
            con.cn_status = CON_NULL;
            theSim.enqueue(new SimEvent(MY_SENDCELL,this,this,theSim.now()+getDelay(),con));
          }
          break;
      }
    }
    else {
      long interval=SimClock.USec2Tick(cn_start_time.getValue());
      interval+=getStartDelay();
      theSim.enqueue(new SimEvent(MY_START,this,this,theSim.now()+interval,con));
    }
  }

//helper function to set a random destination
//return false if can't find a target
  private boolean setRandomTarget(UDPCon con) {
    java.util.List allcomps=theSim.getSimComponents();
    java.util.List ips=new java.util.ArrayList();
    java.util.List ports=new java.util.ArrayList();

    int i,j,k;
    for(i=0;i<allcomps.size();i++) {
      SimComponent comp=(SimComponent)allcomps.get(i);
      if(comp==neighbor(0)) continue; //skip it's own host
      if(comp.getCompClass().equals("Router")) {
        java.util.List thisips=(java.util.List)comp.compInfo(IPRouter.GET_ALL_IP,this,null);
        java.util.List thisports=(java.util.List)comp.compInfo(IPRouter.GET_ALL_PORT,this,null);
        for(j=0;j<thisips.size();j++) {
          for(k=0;k<thisports.size();k+=2) {
            int thisprotocol=((Integer)thisports.get(k+1)).intValue();
            if(thisprotocol==MY_PROTOCOL) {
              ips.add(thisips.get(j));
              ports.add(thisports.get(k));
            }
          }
        }
      }
    }
    if(ips.isEmpty()) return false;

    int choice=randgen.nextInt(ips.size());
    con.con_destip.setValue(((Integer)ips.get(choice)).intValue());
    con.con_destport.setValue(((Integer)ports.get(choice)).intValue());
    return true;
  }

//helper function to get the random delay (if specified by user)
//return in ticks
  private long getDelay() {
    double delay=cn_delay.getValue();
    if(cn_random_delay.getValue()) {
      delay= -delay * Math.log(1.0 - randgen.nextDouble());
    }
    return SimClock.USec2Tick(delay);
  }

//helper function to get the random start delay (if specified by user)
//return in ticks
  private long getStartDelay() {
    double delay=cn_start_delay.getValue();
    if(cn_random_delay.getValue()) {
      delay= -delay * Math.log(1.0 - randgen.nextDouble());
    }
    return SimClock.USec2Tick(delay);
  }

//helper function to get the random transmission size (if specified by user)
//return in number of packets
  private int getTransSize() {
    double size=cn_trans_size1.getValue();
    if(cn_random_size.getValue()) {
      double delta=cn_trans_size2.getValue()-cn_trans_size1.getValue();
      size+=randgen.nextDouble()*delta;
    }
    if(size<0) size=0;
    return (int)(size * 1024 / cn_packet_size.getValue());
  }

  private void cn_receive(SimEvent e) {
    cn_udp.receive_ip((IPPacket)e.getParams(),null);
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -