#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;
}