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<hostNumber;j++){
            virtualHosts[j]=new VirtualHost(""+j,transNumber,delayTime);
        }
        //Starting host threads (start sending)
        for (int i = 0; i < hostNumber; i++) {
            virtualHosts[i].start();
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,093评论 25 709
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,395评论 11 349
  • 2D仿射变换 UIView的transform属性是一个CGAffineTransform类型,用于在二维空间做旋...
    RY_zheng阅读 2,212评论 0 3
  • 你模糊的轮廓 走进了我的视线 走近了我 脸上紧张的红晕 暴露了我的羞涩 窗外的光 转动着你黑色的影子 悄悄的 你把...
    独角灰羚阅读 171评论 0 1
  • 今晚本以为可以和你视频通话的。 哈哈哈,谁知道你那么胆小。 其实我也很紧张,没和父母以外的人视频过,心脏砰砰砰地跳...
    阿煦阅读 180评论 0 1