计算机网络协议模拟程序——滑动窗口协议

来源:互联网 发布:java和javaweb哪个好 编辑:程序博客网 时间:2024/05/20 10:21

百度百科:滑动窗口协议,是TCP使用的一种流量控制的方法。该协议允许发送方在停止并等待确认前可以连续发送多个分组。由于发送方不必每发一个分组就停下来等待确认,因此该协议可以加速数据的传输。


#include<iostream>#include<conio.h>#include<windows.h>#include<cstdlib>using namespace std;class Protocol           //定义一个协议类{public:       Protocol(int m,int c,int n);      //协议类的构造函数       void Sender();                    //发送方函数       bool Reciever();                  //接收方函数private:        int MAXSIZE;                     //定义发送窗口        int count;                       //定义一个在程序中用到的辅助计数变量        int number;                      //定义窗口中用来循环发送消息的序列号        bool ackNumber;                  //定义为bool类型的确认号变量};Protocol::Protocol(int m,int c,int n)     //定义Protocol类的构造函数,用来初始化成员变量{    MAXSIZE=m;    count=c;    number=n;}bool Protocol::Reciever()     //定义接收方函数{     int random;     srand((unsigned)time(NULL));     random=rand()%10;     if(random<=7)           //产生0-7时代表网络通信正常,8-9时代表网络中出现通信错误     return true;     else     return false;}void Protocol::Sender()     //定义发送方函数{     int Queue[MAXSIZE-1];       //使用了代表缓存区的循环队列     int front=0;     int rear=0;     cout<<"----------------The Stimulating Programme Of DataLink Protocol Five.-----------"<<endl;     while(number<=MAXSIZE)     {       Sleep(1000);       cout<<"The Sender is Sending the No."<<number<<" message\n";       Queue[rear]=number;       rear=(rear+1)%(MAXSIZE-1);       if(count>=6)       {            ackNumber=Reciever();            if(!ackNumber)              //当网络通信出现错误时,重发定时器超时的那一帧            {                front=(rear+6)%6;                number=Queue[front];                for(int i=0;i<7;i++)                Queue[i]=0;                cout<<"The No."<<number<<" is Out Time.So We Need To Send Again."<<endl;                count=-1;            }            else            number=(number+1)%MAXSIZE;       }       else       {            number=(number+1)%MAXSIZE;         //循环的发送序号       }       count++;     }}int main(){    Protocol protocol(8,0,0);         //实例化一个协议,并将其最大发送窗口定义为8    protocol.Sender();    system("PAUSE");    return 0;}


原创粉丝点击