justuuu
unknown
plain_text
2 months ago
2.4 kB
3
Indexable
#include<stdio.h> #include<string.h> #include<sys/socket.h> #include<sys/types.h> #include<arpa/inet.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h> #define timeoutvalue 5 #define packetcount 10 #define windowsize 3 typedef struct Packet { int id; int send; }Packet; Packet packets[packetcount]; pthread_t thread[packetcount],receiveThread; int sockfd; struct sockaddr_in addr; int windowStart,windowEnd; int nextToSend; void*sendPacket(void*sendPacket) { Packet*packet=(Packet*)sendPacket; char buffer[1024]; while(packet->send==0) { printf("client:sending packet %d\n",packet->id); bzero(buffer,1024); sprintf(buffer,"%d",packet->id); sendto(sockfd,buffer,1024,0,(struct sockaddr*)&addr,sizeof(addr)); sleep(timeoutvalue); if(packet->send==0) printf("client:timeout for packet %d\n",packet->id); } } void*receivePacket() { socklen_t addr_size=sizeof(addr); char buffer[1024]; while(1) { bzero(buffer,1024); recvfrom(sockfd,buffer,1024,0,(struct sockaddr*)&addr,&addr_size); char msg[20]; int packetID; sscanf(buffer,"%s%d",msg,&packetID); if(strcmp(msg,"NACK")==0) { printf("client received -ve acknowledgement for packet %d \n sending again\n",packetID); pthread_cancel(thread[packetID-1]); pthread_create(&thread[packetID-1],NULL,sendPacket,(void*)&packets[packetID-1]); } else if(strcmp(msg,"ACK")==0) { printf("client:recieved acknowledgemnt for packet %d\n",packetID); packets[packetID-1].send=1; if(windowStart==packetID-1) { while(packets[windowStart].send==1) { windowStart++; if(windowEnd<packetcount) windowEnd++; } } } else printf("client:invalidmessage\n"); } } void main() { for(int i=0;i<packetcount;++i) { packets[i].id=i+1; packets[i].send=0; } char*ip="127.0.0.100"; int port=5570; char buffer[1024]; socklen_t addr_size; sockfd=socket(AF_INET,SOCK_DGRAM,0); if(sockfd<0) { perror("[-]socket error \n"); exit(1); } memset(&addr,'\0',sizeof(addr)); addr.sin_family=AF_INET; addr.sin_port=htons(port); addr.sin_addr.s_addr=inet_addr(ip); pthread_create(&receiveThread,NULL,receivePacket,NULL); windowStart=0; windowEnd=windowStart+windowsize-1; for(int i=windowStart;i<=windowEnd;++i) pthread_create(&thread[i],NULL,sendPacket,(void*)&packets[i]); nextToSend=windowEnd+1; while(windowStart!=windowEnd) { if(nextToSend<=windowEnd && nextToSend<packetcount) { pthread_create(&thread[nextToSend],NULL,sendPacket,(void*)&packets[nextToSend]); nextToSend++; } } close(sockfd); }
Editor is loading...
Leave a Comment