资源描述:
《socket实现停止等待协议 发送端》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、socket实现停止等待协议发送端//发送端#include#include#include#include#include#pragmacomment(lib,"WS2_32.LIB")structsockaddr_insoc_add;//定义地址信息intVS,NS,count,rev_info;intadd_length=sizeof(soc_add);//地址的长度charbuf[100],temp[10];//buf为输入数据缓冲区,temp是发送
2、数据缓冲区voidmain(){WSADATAwsaData;//socket初始化WSAStartup(0x0101,&wsaData);//启动WSAsoc_add.sin_family=AF_INET;//地址初始化soc_add.sin_port=htons(9999);//端口号设置soc_add.sin_addr.s_addr=INADDR_ANY;//本地IPintcalls=0;inti=0,j,argp=1,sd,sd1;//定义接口charch,signal;charinfo[20];FILE*fp;sd=socket(AF_I
3、NET,SOCK_STREAM,0);//套接字创建if(sd<0){printf("创建Socket失败!");exit(1);}if(bind(sd,(structsockaddr*)&soc_add,sizeof(soc_add))<0){//地址与接口绑定printf("绑定失败!");exit(0);}if(listen(sd,5)<0){//创建套接口并监听连接printf("监听失败!");exit(1);}if((sd1=accept(sd,(structsockaddr*)&soc_add,&add_length))<
4、0){//接受一个连接printf("接受失败!");exit(1);}ioctlsocket(sd1,FIONBIO,(u_longFAR*)&argp);//设置套接字为非阻塞状态printf("请输入所需发送的信息:");ch=getchar();//输入所需发送的信息while(ch!=10){buf[i]=ch;i++;ch=getchar();}i=0;fp=fopen("sent.txt","w");while(1){calls=0;NS=VS;//temp中为控制字符以及一段即将发送的符号temp[calls++]=0x02;t
5、emp[calls++]=(char)(NS+48);do{//这个循环是将存在缓冲区的中的输入数据4个字符4个字符的存入temp数组中temp[calls++]=buf[i];i++;}while(i%4!=0&&buf[i]!='');while(calls!=6)temp[calls++]=0x1B;temp[calls++]=0x03;do{send(sd1,temp,sizeof(temp),0);//开始发送Sleep(1000);//延迟1s,便于观察程序运行情况printf("发送:");strcpy(info,"发送:");fpu
6、ts(info,fp);for(j=0;j<4;j++)if(temp[j+2]!=0x1B){printf("%c",temp[j+2]);fputc(temp[j+2],fp);}printf("");fputs("",fp);if(temp[2]==NULL){//通知接收方一次数据已经发送完毕signal=0x04;send(sd1,&signal,1,0);exit(0);}rev_info=recv(sd1,buf,sizeof(buf),0);//接收反馈信息if(buf[0]==0x15){//在屏幕输出返回结果并且存入文件
7、之中printf("接收:NAK");//NAK表示未确认info[20]=NULL;strcpy(info,"接收:NAK");fputs(info,fp);}if(rev_info==SOCKET_ERROR){//在屏幕输出返回结果并且存入文件之中printf("接收:超时!");info[20]=NULL;strcpy(info,"接收:超时!");fputs(info,fp);}}while(rev_info==SOCKET_ERROR
8、
9、buf[0]==0x15);if(rev_info!=SOCKET_ERROR){c
10、ount=(int)buf[0];//count是帧编号if(count==VS){//在屏幕输出返回结果并且存入文件之中