计算机网络Stop-and-Wait协议实现(C语言)
文章目录
前言
实现单向传输情景下的Stop-and-Wait
主要是填充实验给出的空函数块
一、总代码
#include <stdio.h>
#include <string.h>
/* ******************************************************************
ALTERNATING BIT AND GO-BACK-N NETWORK EMULATOR: VERSION 1.1 J.F.Kurose
This code should be used for PA2, unidirectional or bidirectional
data transfer protocols (from A to B. Bidirectional transfer of data
is for extra credit and is not required). Network properties:
- one way network delay averages five time units (longer if there
are other messages in the channel for GBN), but can be larger
- packets can be corrupted (either the header or the data portion)
or lost, according to user-defined probabilities
- packets will be delivered in the order in which they were sent
(although some can be lost).
**********************************************************************/
#define BIDIRECTIONAL 0 /* change to 1 if you're doing extra credit */
/* and write a routine called B_output */
/* a "msg" is the data unit passed from layer 5 (teachers code) to layer */
/* 4 (students' code). It contains the data (characters) to be delivered */
/* to layer 5 via the students transport level protocol entities. */
struct msg {
char data[20];//传输数据
};
/* a packet is the data unit passed from layer 4 (students code) to layer */
/* 3 (teachers code). Note the pre-defined packet structure, which all */
/* students must follow. */
struct pkt {
int seqnum;//发送序号
int acknum;//确认序号
int checksum;//检查是否出错序号
char payload[20];//发送窗口大小
};
/********* STUDENTS WRITE THE NEXT SEVEN ROUTINES *********/
#define OK 1
#define ERROR 0
typedef struct msg msg;
typedef struct pkt pkt;
void ComputeCheckSum(pkt* packet){
packet->checksum = packet->seqnum + packet->acknum;
int i;
for(i = 0;i < 20;i += 4){
int tmp1 = (int)packet->payload[i];
int tmp2 = (int)packet->payload[i + 1];
int tmp3 = (int)packet->payload[i + 2];
int tmp4 = (int)packet->payload[i + 3];
tmp2 *= 256;
tmp3 *= 65536;
tmp4 *= 16777216;
packet->checksum += (tmp1 + tmp2 + tmp3 + tmp4);
}
packet->checksum = ~ packet->checksum;
}//设置较错码
int TestCheckSum(pkt* packet){
int check = packet->checksum;
check += (packet->seqnum + packet->acknum);
int i;
for(i = 0;i < 20;i += 4){
int tmp1 = (int)packet->payload[i];
int tmp2 = (int)packet->payload[i + 1];
int tmp3 = (int)packet->payload[i + 2];
int tmp4 = (int)packet->payload[i + 3];
tmp2 *= 256;
tmp3 *= 65536;
tmp4 *= 16777216;
check += (tmp1 + tmp2 + tmp3 + tmp4);
}
return check;
}//检测收到的较错码,确认收到的包是否有误
int A_sequenceNum = 0;
int Ajudge = 1;//判断发送端是否能发送包
float A_interval = 25.0;//重发时间间隔
int B_sequenceNum = 0;
char ACK[20] = "ACK";
char NAK[20] = "NAK";
pkt A_pkt;
pkt B_pkt;
/* called from layer 5, passed the data to be sent to other side */
A_output(message)
struct msg message;
{
if(Ajudge){
strncpy(A_pkt.payload,message.data,20);//从message截取20字节放到payload内
int n;
A_pkt.seqnum = A_sequenceNum;
A_pkt.acknum = 0;
A_sequenceNum = (A_sequenceNum + 1) % 2;//发送包序号1与0之间切换
Ajudge = 0;
ComputeCheckSum(&A_pkt);
tolayer3(0,A_pkt); //发送
starttimer(0,A_interval); //开始计时
printf("A: sending:\n");
printf(" seq:%d, ack:%d check:%X\n",A_pkt.seqnum,A_pkt.acknum,A_pkt.checksum);
printf(" message: ");
for(n = 0;n < 20;n ++) printf("%c",A_pkt.payload[n]);
printf("\n");
}
return OK;
}
B_output(message) /* need be completed only for extra credit */
struct msg message;
{
}
/* called from layer 3, when a packet arrives for layer 4 */
A_input(packet)
struct pkt packet;
{
printf("receive scknum:%d,looking for:%d\n",packet.acknum,(A_sequenceNum + 1) % 2);
int point_num = (A_sequenceNum + 1) % 2;
if(point_num != packet.acknum)
return ERROR;
if(TestCheckSum(&packet) == -1){
if(!strcmp(packet.payload,ACK)){
printf("ACK!\n");
Ajudge = 1;
stoptimer(0);
return OK;
}//如果收到ACK,将Ajudge置1进行下一个包的传输
else{
printf("NAK!\n");
tolayer3(0,A_pkt);
starttimer(0,A_interval);
return OK;
}//收到NAK,重新发包,重置定时器
}
else{
printf("corrupted!\n");
return ERROR;
}
return OK;
}
/* called when A's timer goes off */
A_timerinterrupt()
{
tolayer3(0,A_pkt);
starttimer(0,A_interval);
int n;
printf("sending:\n");
printf(" seq:%d, ack:%d check:%X\n",A_pkt.seqnum,A_pkt.acknum,A_pkt.checksum);
printf(" message:");
for(n = 0;n < 20;n ++) printf("%c",A_pkt.payload[n]);
printf("\n\n");
return OK;
} //重发
/* the following routine will be called once (only) before any other */
/* entity A routines are called. You can use it to do any initialization */
A_init()
{
A_sequenceNum = 0;
Ajudge = 1;
return OK;
}
/* Note that with simplex transfer from a-to-B, there is no B_output() */
/* called from layer 3, when a packet arrives for layer 4 at B*/
B_input(packet)
struct pkt packet;
{
int n;
printf("receiving:\n");
printf(" seq:%d, ack:%d check:%X\n",packet.seqnum,packet.acknum,packet.checksum);
printf(" message:");
for(n = 0;n < 20;n ++) printf("%c",packet.payload[n]);
printf("\n\n");
printf("receive:%d,looking for:%d\n",packet.seqnum,B_sequenceNum);
if(packet.seqnum != B_sequenceNum){
tolayer3(1,B_pkt);
printf("B:sending:\n");
printf(" seq:%d, ack:%d check:%X\n",B_pkt.seqnum,B_pkt.acknum,B_pkt.checksum);
printf(" message:");
for(n = 0;n < 20;n ++) printf("%c",B_pkt.payload[n]);
printf("\n\n");
return OK;
}//处理发送包序号在过程中改变的情况,B端回复与上次之前的包
B_pkt.seqnum = 0;
B_pkt.acknum = B_sequenceNum;
if(TestCheckSum(&packet) == -1){
strncpy(B_pkt.payload,ACK,20);
msg receive;
strncpy(receive.data,packet.payload,20);
tolayer5(1,receive);
B_sequenceNum = (B_sequenceNum + 1) % 2;
}//收到的包没有损坏
else{
strncpy(B_pkt.payload,NAK,20);
ComputeCheckSum(&B_pkt);
printf("B:sending:\n");
printf(" seq:%d, ack:%d check:%X\n",B_pkt.seqnum,B_pkt.acknum,B_pkt.checksum);
printf(" message:");
for(n = 0;n < 20;n ++) printf("%c",B_pkt.payload[n]);
printf("\n\n");
tolayer3(1,B_pkt);
return OK;
}//收到的包与发送不一致
}
/* called when B's timer goes off */
B_timerinterrupt()
{
return OK;
}
/* the following rouytine will be called once (only) before any other */
/* entity B routines are called. You can use it to do any initialization */
B_init()
{
B_sequenceNum = 0;
return OK;
}
/*****************************************************************
***************** NETWORK EMULATION CODE STARTS BELOW ***********
The code below emulates the layer 3 and below network environment:
- emulates the tranmission and delivery (possibly with bit-level corruption
and packet loss) of packets across the layer 3/4 interface
- handles the starting/stopping of a timer, and generates timer
interrupts (resulting in calling students timer handler).
- generates message to be sent (passed from later 5 to 4)
THERE IS NOT REASON THAT ANY STUDENT SHOULD HAVE TO READ OR UNDERSTAND
THE CODE BELOW. YOU SHOLD NOT TOUCH, OR REFERENCE (in your code) ANY
OF THE DATA STRUCTURES BELOW. If you're interested in how I designed
the emulator, you're welcome to look at the code - but again, you should have
to, and you defeinitely should not have to modify
******************************************************************/
struct event {
float evtime; /* event time */
int evtype; /* event type code */
int eventity; /* entity where event occurs */
struct pkt *pktptr; /* ptr to packet (if any) assoc w/ this event */
struct event *prev;
struct event *next;
};
struct event *evlist = NULL; /* the event list */
/* possible events: */
#define TIMER_INTERRUPT 0
#define FROM_LAYER5 1
#define FROM_LAYER3 2
#define OFF 0
#define ON 1
#define A 0
#define B 1
int TRACE = 1; /* for my debugging */
int nsim = 0; /* number of messages from 5 to 4 so far */
int nsimmax = 0; /* number of msgs to generate, then stop */
float time = 0.000;
float lossprob; /* probability that a packet is dropped */
float corruptprob; /* probability that one bit is packet is flipped */
float lambda; /* arrival rate of messages from layer 5 */
int ntolayer3; /* number sent into layer 3 */
int nlost; /* number lost in media */
int ncorrupt; /* number corrupted by media*/
main()
{
struct event *eventptr;
struct msg msg2give;
struct pkt pkt2give;
int i,j;
char c;
init();
A_init();
B_init();
while (1) {
eventptr = evlist; /* get next event to simulate */
if (eventptr==NULL)
goto terminate;
evlist = evlist->next; /* remove this event from event list */
if (evlist!=NULL)
evlist->prev=NULL;
if (TRACE>=2) {
printf("\nEVENT time: %f,",eventptr->evtime);
printf(" type: %d",eventptr->evtype);
if (eventptr->evtype==0)
printf(", timerinterrupt ");
else if (eventptr->evtype==1)
printf(", fromlayer5 ");
else
printf(", fromlayer3 ");
printf(" entity: %d\n",eventptr->eventity);
}
time = eventptr->evtime; /* update time to next event time */
if (nsim==nsimmax)
break; /* all done with simulation */
if (eventptr->evtype == FROM_LAYER5 ) {
generate_next_arrival(); /* set up future arrival */
/* fill in msg to give with string of same letter */
j = nsim % 26;
for (i=0; i<20; i++)
msg2give.data[i] = 97 + j;
if (TRACE>2) {
printf(" MAINLOOP: data given to student: ");
for (i=0; i<20; i++)
printf("%c", msg2give.data[i]);
printf("\n");
}
nsim++;
if (eventptr->eventity == A)
A_output(msg2give);
else
B_output(msg2give);
}
else if (eventptr->evtype == FROM_LAYER3) {
pkt2give.seqnum = eventptr->pktptr->seqnum;
pkt2give.acknum = eventptr->pktptr->acknum;
pkt2give.checksum = eventptr->pktptr->checksum;
for (i=0; i<20; i++)
pkt2give.payload[i] = eventptr->pktptr->payload[i];
if (eventptr->eventity ==A) /* deliver packet by calling */
A_input(pkt2give); /* appropriate entity */
else
B_input(pkt2give);
free(eventptr->pktptr); /* free the memory for packet */
}
else if (eventptr->evtype == TIMER_INTERRUPT) {
if (eventptr->eventity == A)
A_timerinterrupt();
else
B_timerinterrupt();
}
else {
printf("INTERNAL PANIC: unknown event type \n");
}
free(eventptr);
}
terminate:
printf(" Simulator terminated at time %f\n after sending %d msgs from layer5\n",time,nsim);
}
init() /* initialize the simulator */
{
int i;
float sum, avg;
float jimsrand();
printf("----- Stop and Wait Network Simulator Version 1.1 -------- \n\n");
printf("Enter the number of messages to simulate: ");
scanf("%d",&nsimmax);
printf("Enter packet loss probability [enter 0.0 for no loss]:");
scanf("%f",&lossprob);
printf("Enter packet corruption probability [0.0 for no corruption]:");
scanf("%f",&corruptprob);
printf("Enter average time between messages from sender's layer5 [ > 0.0]:");
scanf("%f",&lambda);
printf("Enter TRACE:");
scanf("%d",&TRACE);
srand(9999); /* init random number generator */
sum = 0.0; /* test random number generator for students */
for (i=0; i<1000; i++)
sum=sum+jimsrand(); /* jimsrand() should be uniform in [0,1] */
avg = sum/1000.0;
if (avg < 0.25 || avg > 0.75) {
printf("It is likely that random number generation on your machine\n" );
printf("is different from what this emulator expects. Please take\n");
printf("a look at the routine jimsrand() in the emulator code. Sorry. \n");
exit(-1);
}
ntolayer3 = 0;
nlost = 0;
ncorrupt = 0;
time=0.0; /* initialize time to 0.0 */
generate_next_arrival(); /* initialize event list */
}
/****************************************************************************/
/* jimsrand(): return a float in range [0,1]. The routine below is used to */
/* isolate all random number generation in one location. We assume that the*/
/* system-supplied rand() function return an int in therange [0,mmm] */
/****************************************************************************/
float jimsrand()
{
double mmm = 32767; /* largest int - MACHINE DEPENDENT!!!!!!!! */
float x; /* individual students may need to change mmm */
x = rand()/mmm; /* x should be uniform in [0,1] */
return(x);
}
/********************* EVENT HANDLINE ROUTINES *******/
/* The next set of routines handle the event list */
/*****************************************************/
generate_next_arrival()
{
double x,log(),ceil();
struct event *evptr;
char *malloc();
float ttime;
int tempint;
if (TRACE>2)
printf(" GENERATE NEXT ARRIVAL: creating new arrival\n");
x = lambda*jimsrand()*2; /* x is uniform on [0,2*lambda] */
/* having mean of lambda */
evptr = (struct event *)malloc(sizeof(struct event));
evptr->evtime = time + x;
evptr->evtype = FROM_LAYER5;
if (BIDIRECTIONAL && (jimsrand()>0.5) )
evptr->eventity = B;
else
evptr->eventity = A;
insertevent(evptr);
}
insertevent(p)
struct event *p;
{
struct event *q,*qold;
if (TRACE>2) {
printf(" INSERTEVENT: time is %lf\n",time);
printf(" INSERTEVENT: future time will be %lf\n",p->evtime);
}
q = evlist; /* q points to header of list in which p struct inserted */
if (q==NULL) { /* list is empty */
evlist=p;
p->next=NULL;
p->prev=NULL;
}
else {
for (qold = q; q !=NULL && p->evtime > q->evtime; q=q->next)
qold=q;
if (q==NULL) { /* end of list */
qold->next = p;
p->prev = qold;
p->next = NULL;
}
else if (q==evlist) { /* front of list */
p->next=evlist;
p->prev=NULL;
p->next->prev=p;
evlist = p;
}
else { /* middle of list */
p->next=q;
p->prev=q->prev;
q->prev->next=p;
q->prev=p;
}
}
}
printevlist()
{
struct event *q;
int i;
printf("--------------\nEvent List Follows:\n");
for(q = evlist; q!=NULL; q=q->next) {
printf("Event time: %f, type: %d entity: %d\n",q->evtime,q->evtype,q->eventity);
}
printf("--------------\n");
}
/********************** Student-callable ROUTINES ***********************/
/* called by students routine to cancel a previously-started timer */
stoptimer(AorB)
int AorB; /* A or B is trying to stop timer */
{
struct event *q,*qold;
if (TRACE>2)
printf(" STOP TIMER: stopping timer at %f\n",time);
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==TIMER_INTERRUPT && q->eventity==AorB) ) {
/* remove this event */
if (q->next==NULL && q->prev==NULL)
evlist=NULL; /* remove first and only event on list */
else if (q->next==NULL) /* end of list - there is one in front */
q->prev->next = NULL;
else if (q==evlist) { /* front of list - there must be event after */
q->next->prev=NULL;
evlist = q->next;
}
else { /* middle of list */
q->next->prev = q->prev;
q->prev->next = q->next;
}
free(q);
return;
}
printf("Warning: unable to cancel your timer. It wasn't running.\n");
}
starttimer(AorB,increment)
int AorB; /* A or B is trying to stop timer */
float increment;
{
struct event *q;
struct event *evptr;
char *malloc();
if (TRACE>2)
printf(" START TIMER: starting timer at %f\n",time);
/* be nice: check to see if timer is already started, if so, then warn */
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==TIMER_INTERRUPT && q->eventity==AorB) ) {
printf("Warning: attempt to start a timer that is already started\n");
return;
}
/* create future event for when timer goes off */
evptr = (struct event *)malloc(sizeof(struct event));
evptr->evtime = time + increment;
evptr->evtype = TIMER_INTERRUPT;
evptr->eventity = AorB;
insertevent(evptr);
}
/************************** TOLAYER3 ***************/
tolayer3(AorB,packet)
int AorB; /* A or B is trying to stop timer */
struct pkt packet;
{
struct pkt *mypktptr;
struct event *evptr,*q;
char *malloc();
float lastime, x, jimsrand();
int i;
ntolayer3++;
/* simulate losses: */
if (jimsrand() < lossprob) {
nlost++;
if (TRACE>0)
printf(" TOLAYER3: packet being lost\n");
return;
}
/* make a copy of the packet student just gave me since he/she may decide */
/* to do something with the packet after we return back to him/her */
mypktptr = (struct pkt *)malloc(sizeof(struct pkt));
mypktptr->seqnum = packet.seqnum;
mypktptr->acknum = packet.acknum;
mypktptr->checksum = packet.checksum;
for (i=0; i<20; i++)
mypktptr->payload[i] = packet.payload[i];
if (TRACE>2) {
printf(" TOLAYER3: seq: %d, ack %d, check: %d ", mypktptr->seqnum,
mypktptr->acknum, mypktptr->checksum);
for (i=0; i<20; i++)
printf("%c",mypktptr->payload[i]);
printf("\n");
}
/* create future event for arrival of packet at the other side */
evptr = (struct event *)malloc(sizeof(struct event));
evptr->evtype = FROM_LAYER3; /* packet will pop out from layer3 */
evptr->eventity = (AorB+1) % 2; /* event occurs at other entity */
evptr->pktptr = mypktptr; /* save ptr to my copy of packet */
/* finally, compute the arrival time of packet at the other end.
medium can not reorder, so make sure packet arrives between 1 and 10
time units after the latest arrival time of packets
currently in the medium on their way to the destination */
lastime = time;
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==FROM_LAYER3 && q->eventity==evptr->eventity) )
lastime = q->evtime;
evptr->evtime = lastime + 1 + 9*jimsrand();
/* simulate corruption: */
if (jimsrand() < corruptprob) {
ncorrupt++;
if ( (x = jimsrand()) < .75)
mypktptr->payload[0]='Z'; /* corrupt payload */
else if (x < .875)
mypktptr->seqnum = 999999;
else
mypktptr->acknum = 999999;
if (TRACE>0)
printf(" TOLAYER3: packet being corrupted\n");
}
if (TRACE>2)
printf(" TOLAYER3: scheduling arrival on other side\n");
insertevent(evptr);
}
tolayer5(AorB,datasent)
int AorB;
char datasent[20];
{
int i;
if (TRACE>2) {
printf(" TOLAYER5: data received: ");
for (i=0; i<20; i++)
printf("%c",datasent[i]);
printf("\n");
}
}
二、代码块
1.直接利用的函数
starttimer(calling_entity,increment)
其中calling_entity为0(用于启动a端计时器)或1(用于启动B端计时器),increment是一个浮点值,表示在计时器中断之前将经过的时间。A的计时器应该只由A端例程启动(或停止),b端计时器也是如此。给我们一个可以使用的适当增量值的概念:当媒体中没有其他消息时,发送到网络的数据包平均需要5个时间单位到达另一端。
stoptimer(calling_entity)
其中calling_entity为0(用于停止a端定时器)或1(用于停止B端定时器)。
tolayer3(calling_entity,packet)
其中calling_entity为0(用于a端发送)或1(用于B端发送),并且packet是一个类型为pkt的结构。调用这个例程将导致数据包被发送到网络中,目的地是另一个实体。
tolayer5(calling_entity,message)
其中calling_entity为0(对于a端发送到第5层)或1(对于b端发送到第5层),message是一个msg类型的结构。对于单向数据传输,我们将只调用calling_entity等于1(交付到b端)。调用这个例程将导致数据被传递到第5层。
2.结构体
两个在后面函数频繁用到的结构体,msg结构就是代表一个存储信息的数组,pkt代表一个包,题目中有A端,B端,默认A端发送包,B端将收到无误的包传给上层,以及根据包的对错发送NAK和ACK,所以对于A端pkt中的acknum一直为0,B端seqnum一直为1.
struct msg {
char data[20];//传输数据
};
/* a packet is the data unit passed from layer 4 (students code) to layer */
/* 3 (teachers code). Note the pre-defined packet structure, which all */
/* students must follow. */
struct pkt {
int seqnum;//发送序号
int acknum;//确认序号
int checksum;//检查是否出错序号
char payload[20];//发送窗口大小
};
3.较错码
为防止两端收到的包出现被破坏的情况,在发送端设置了较错码,即pkt的checksum,在接收端定义了检测较错码的函数,通过取反加一的规律构造函数
void ComputeCheckSum(pkt* packet){
packet->checksum = packet->seqnum + packet->acknum;
int i;
for(i = 0;i < 20;i += 4){
int tmp1 = (int)packet->payload[i];
int tmp2 = (int)packet->payload[i + 1];
int tmp3 = (int)packet->payload[i + 2];
int tmp4 = (int)packet->payload[i + 3];
tmp2 *= 256;
tmp3 *= 65536;
tmp4 *= 16777216;
packet->checksum += (tmp1 + tmp2 + tmp3 + tmp4);
}
packet->checksum = ~ packet->checksum;
}//设置较错码
int TestCheckSum(pkt* packet){
int check = packet->checksum;
check += (packet->seqnum + packet->acknum);
int i;
for(i = 0;i < 20;i += 4){
int tmp1 = (int)packet->payload[i];
int tmp2 = (int)packet->payload[i + 1];
int tmp3 = (int)packet->payload[i + 2];
int tmp4 = (int)packet->payload[i + 3];
tmp2 *= 256;
tmp3 *= 65536;
tmp4 *= 16777216;
check += (tmp1 + tmp2 + tmp3 + tmp4);
}
return check;
}//检测收到的较错码,确认收到的包是否有误
4.变量
AB两端用到的变量
int A_sequenceNum = 0;
int Ajudge = 1;//判断发送端是否能发送包
float A_interval = 25.0;//重发时间间隔
int B_sequenceNum = 0;
char ACK[20] = "ACK";
char NAK[20] = "NAK";
pkt A_pkt;
pkt B_pkt;
5.A_output函数
其中message是msg类型的结构,包含要发送到b端的数据。这个例程将在发送侧(A)的上层有消息要发送时被调用。我们的协议的工作是确保这样一个消息中的数据被按顺序和正确地发送到接收方的上层。
A_output(message)
struct msg message;
{
if(Ajudge){
strncpy(A_pkt.payload,message.data,20);//从message截取20字节放到payload内
int n;
A_pkt.seqnum = A_sequenceNum;
A_pkt.acknum = 0;
A_sequenceNum = (A_sequenceNum + 1) % 2;//发送包序号1与0之间切换
Ajudge = 0;
ComputeCheckSum(&A_pkt);
tolayer3(0,A_pkt); //发送
starttimer(0,A_interval); //开始计时
printf(“A: sending:\n”);
printf(" seq:%d, ack:%d check:%X\n",A_pkt.seqnum,A_pkt.acknum,A_pkt.checksum);
printf(" message: “);
for(n = 0;n < 20;n ++) printf(”%c",A_pkt.payload[n]);
printf("\n");
}
return OK;
}
6.A_input函数
其中packet是pkt类型的结构。这个例程将在从b端发送的数据包到达a端时被调用(例如,由于b端过程执行tolayer3())。packet是从b端发送的数据包(可能已损坏)。
A_input(packet)
struct pkt packet;
{
printf("receive scknum:%d,looking for:%d\n",packet.acknum,(A_sequenceNum + 1) % 2);
int point_num = (A_sequenceNum + 1) % 2;
if(point_num != packet.acknum)
return ERROR; //检测包是否被损坏
if(TestCheckSum(&packet) == -1){
if(!strcmp(packet.payload,ACK)){
printf("ACK!\n");
Ajudge = 1;
stoptimer(0);
return OK;
}//如果收到ACK,将Ajudge置1进行下一个包的传输
else{
printf("NAK!\n");
tolayer3(0,A_pkt);
starttimer(0,A_interval);
return OK;
}//收到NAK,重新发包,重置定时器
}
else{
printf("corrupted!\n");
return ERROR;
}
return OK;
}
7.A_timerinterrupt()函数
这个例程将在A的计时器到期时被调用(从而产生一个计时器中断)。我们可能希望使用这个例程来控制数据包的重传。请参阅下面的starttimer()和stoptimer()了解计时器是如何启动和停止的。
A_timerinterrupt()
{
tolayer3(0,A_pkt);
starttimer(0,A_interval);
int n;
printf("sending:\n");
printf(" seq:%d, ack:%d check:%X\n",A_pkt.seqnum,A_pkt.acknum,A_pkt.checksum);
printf(" message:");
for(n = 0;n < 20;n ++) printf("%c",A_pkt.payload[n]);
printf("\n\n");
return OK;
} //重发
8.B_input函数
其中packet是pkt类型的结构。这个例程将在从a端发送的数据包到达b端时被调用(例如,由于a端过程执行tolayer3())。packet是从a端发送的数据包(可能已损坏)。
最难理解的是B端的input函数,先总结一下B端接受信息会碰到的情况
首先需要比较的是包的序号,因为不排除A端包的序号由0变为1的可能性
其次比较包的内容,用到的就是较错码
1)如果包的序号发生改变,B端给的回应包的acknum应该与上次发送一致
if(packet.seqnum != B_sequenceNum){
tolayer3(1,B_pkt);
printf("B:sending:\n");
printf(" seq:%d, ack:%d check:%X\n",B_pkt.seqnum,B_pkt.acknum,B_pkt.checksum);
printf(" message:");
for(n = 0;n < 20;n ++) printf("%c",B_pkt.payload[n]);
printf("\n\n");
return OK;
}//处理发送包序号在过程中改变的情况,B端回复与上次之前的包
2)如果包内容改变(较错码改变)
if(TestCheckSum(&packet) == -1){
strncpy(B_pkt.payload,ACK,20);
msg receive;
strncpy(receive.data,packet.payload,20);
tolayer5(1,receive);
B_sequenceNum = (B_sequenceNum + 1) % 2;
}//收到的包没有损坏
else{
strncpy(B_pkt.payload,NAK,20);
ComputeCheckSum(&B_pkt);
printf("B:sending:\n");
printf(" seq:%d, ack:%d check:%X\n",B_pkt.seqnum,B_pkt.acknum,B_pkt.checksum);
printf(" message:");
for(n = 0;n < 20;n ++) printf("%c",B_pkt.payload[n]);
printf("\n\n");
tolayer3(1,B_pkt);
return OK;
}//收到的包与发送不一致
总结
比较困难的是情况考虑的全面,一直忘记包的序号也会改变这一情况,所以对于信息传输,一定要考虑可能发生的每种情况,以及应对的措施,不然总会有意想不到的结果发生