C语言模拟滑动窗口协议,可自定义发送窗口大小,第一个帧号。帧发送,接收同时发送窗口和接收窗口随之变化。错序接收先存储,待之前的序号到达时一起交给上层程序。
#include
#include
#include
main()
{
struct swphdr
{
unsigned long seqnum;
unsigned long acknum;
unsigned short flags; /*flag=0表示这是一个数据帧,flag=1表示这是一个ACK帧*/
};
struct sendq_slot
{
unsigned short timeout;/*1时表示计时启动,0时表示已收到确认*/
unsigned long msg;
struct sendq_slot *next;
};
struct recvq_slot
{
unsigned short received;/*1表示顺序接收,0表示错序接受*/
unsigned long msg;
struct recvq_slot *next;
};
struct swpstate
{
unsigned long lar;
unsigned long lfs;
unsigned long sws;
struct swphdr hdr;
unsigned long rws;
struct sendq_slot *sendq;
unsigned long nfe;
struct recvq_slot *head;
}swpstate1;
unsigned long a;
int flag,b;
/*发送*/
struct sendq_slot *sendq_rear,*sendp,*p3,*p4;
struct recvq_slot *recvp,*recvq_rear,*p1,*p2;
swpstate1.head=NULL;
swpstate1.sendq=sendq_rear=(struct sendq_slot*)malloc(sizeof(struct sendq_slot));
if(!swpstate1.sendq) exit(1);
sendq_rear->next=NULL;
printf("请输入窗口大小:");
scanf("%ld",&swpstate1.sws);
swpstate1.rws=swpstate1.sws;
if (swpstate1.sws>0)
{
printf("请输入第一帧的序列号:");
scanf("%ld",&swpstate1.hdr.seqnum);
}
swpstate1.nfe=swpstate1.hdr.seqnum;
sendp=(struct sendq_slot*)malloc(sizeof(struct sendq_slot));
if(!sendp) exit(1);
sendp->msg=swpstate1.hdr.seqnum;
sendp->timeout=1;
sendp->next=NULL;
sendq_rear->next=sendp;
sendq_rear=sendp;
--swpstate1.sws;
swpstate1.lfs=swpstate1.hdr.seqnum;
r=swpstate1.hdr.seqnum;
do
{
while(swpstate1.sws>0)
{
sendp=(struct sendq_slot*)malloc(sizeof(struct sendq_slot));
if(!sendp) exit(1);
sendp->msg=swpstate1.lfs+1;
sendp->timeout=1;
sendp->next=NULL;
sendq_rear->next=sendp;
sendq_rear=sendp;
--swpstate1.sws;
++swpstate1.lfs;
}
swpstate1.hdr.acknum=0;
swpstate1.hdr.flags=0;
printf("最近收到的ACK的帧序号:%ld\n",r);
printf("最近发送的帧序号(发送新帧后):%ld\n",swpstate1.lfs);
/*接收*/
if(swpstate1.hdr.flags==0)
{
do
{
printf("请输入收到的数据帧号:");
scanf("%ld",&a);
if(a>=swpstate1.nfe&&a<=swpstate1.lfs)
{
if(swpstate1.head==NULL)
{
recvp=recvq_rear=(struct recvq_slot*)malloc(sizeof(struct recvq_slot));
recvp->next=NULL;
swpstate1.head=recvp;
}
else
if(swpstate1.head!=NULL)
{
recvp=(struct recvq_slot*)malloc(sizeof(struct recvq_slot));
recvp->next=NULL;
recvq_rear->next=recvp;
recvq_rear=recvp;
}
}
else
{
printf("所输数据不在接收窗口内!");
break;
}
recvp->msg=a;
if(recvp->msg==swpstate1.nfe)
recvp->received=1;
else
recvp->rece
如果觉得《c语言实现滑动窗口类 C语言模拟滑动窗口协议》对你有帮助,请点赞、收藏,并留下你的观点哦!