Java模拟CSMA/CD协议

CSMA/CD协议的介绍看这篇文章CSMA/CD协议

本次模拟CSMA/CD协议,涉及到3个java文件

  • **VirtualHost.java : ** 该类继承至线程,我们使用线程来操作一个静态的变量模拟主机之间的通信的过程
  • BackOffTimer.java:计算出发生碰撞后重传推迟的时间
  • CSMACDTest.java:主函数,启动线程,模拟主机之间的通信。

VirtualHost.java

import java.lang.Thread;
/**
* CSMA/CD Host stimulation
* Each Host runs as a thread
* For higher probability of collision, host number should be high
*/

class VirtualHost extends Thread {

    private static int bus = 0;     /** 当前所处的状态*/
    private String name;        /**Hostname */
    private int num;            /**total number of transmissions */
    private int propDelay;      /**sending delay */

    /**
     * Default constructor, for hosts, running a common bus (channel)
     * @param name: Hostname
     * @param total: Total sending number
     * @param propDelay: Propagation delay
     */
    VirtualHost(String name, int total, int propDelay) {
        this.name = name;//主机名称
        num = total; //总共有total个数据帧
        this.propDelay = propDelay;
    }
    public void run() {
        
        //开始循环发送数据
        for (int n = 1; n <= num; n++) {
            //每一个主机在发送数据之前都随机休眠一段时间,模拟主机抢占信道的过程
            try {
                Thread.sleep((int) (Math.random() * propDelay) / 2); 
            } catch (InterruptedException e) { 
                System.err.println("Interrupted: Interrupt exception ");
            }

            int count = 0;  /** 冲突的次数 */
            //try to send: 16 times..
            while (count < 16) {
                //在这里检测信道是否空闲
                if(bus==0) {
                    try {
                        Thread.sleep(propDelay);
                    } catch (InterruptedException e) {
                        System.err.println("Interrupted: Interrupt exception");
                    }
                    bus++;       
                } else {
                    System.out.println("总线忙!!!");
                    continue;
                }
                
                try {
                    Thread.sleep(propDelay); //发送数据中....
                } catch (InterruptedException e) {
                    System.err.println("Interrupted: Interrupt exception");
                }
                
                //bus = 1 means:总线闲, 数据成功发送
                if(bus==1) {
                    System.out.println("Host["+name+"] 第 " +n+ " 个数据帧发送成功!");
                    bus=0;
                    break;
                }
                
                //bus >= 2 means:数据帧在发送的时候发生了碰撞
                if(bus>=2) {
                    count++;
                    System.out.println("Host["+name+"] 第 " + n + " 个数据帧第 " 
                            + count + " 次发送碰撞!");
                    bus=0;
                    //动态退避
                    try {
                        BackoffTimer timer = new BackoffTimer();
                        Thread.sleep(2*propDelay*timer.backoffTime(count));
                    } catch (InterruptedException e) {
                        System.err.println("Interrupted: Interrupt exception");
                    }
                }
            }
            //重传超过16次了, 丢弃该帧,并向高层报告
            if (count >= 16){
                System.out.println("Host[" + name + "] 第 " + n 
                        + " 个数据帧发送失败!");
            }
        }
    }
}

BackoffTimer.java

import java.lang.Math;

/**
 * Backoff timer generator
 */
public class BackoffTimer {
    /**
     *
     * Randomly selected back-off time,
     * Calculated according to the retransmission number
     * random multiples by k times for k-th retransmission
     * @param transNum  : number of rretransmission
     * @return Random multiples
     */
    public int backoffTime(int transNum) { 
        int random;
        int temp;
        temp=Math.min(transNum,10);
        random=(int)(Math.random()*(Math.pow(2,temp)-1));
        return random;
    }
}

CSMACDTest.java

import java.util.Scanner;

/**
 * CSMA/CD Simulator
 */
public class CSMACDTest {
    public static void main(String[] args) {
        
        int hostNumber; /** 主机个数 */
        int transNumber;    /** 发送数据的个数*/
        int delayTime;      /** 传播延迟*/
        
        Scanner scan = new Scanner(System.in);
        //Number of Clients
        System.out.println("Enter the number of hosts:");
        hostNumber=scan.nextInt();
         
        // Number of transmissions  发送数据的个数
        System.out.println("Enter the number of transmissions:(per host)");
        transNumber=scan.nextInt();
               
        //Propagation delay
        System.out.println("Enter the propagation delay time:");
        delayTime=scan.nextInt();
         
        //Array container of virtual hosts
        VirtualHost[] virtualHosts=new VirtualHost[hostNumber];
        //Assign each virtual host thread to each of the virtual hosts
        for(int j=0;j

你可能感兴趣的:(Java模拟CSMA/CD协议)