I have server that is sending udp datagrams to client and receiving NACK datagrams from client if packet is lost. I want to create thread that will process every NACK packet but I want to create thread only if I have something to receive from the client. For that I thought to use select , if there is something on socket then create new thread and call recvfrom fucntion. I define timeval struct and fill it with 0 because I don't want to wait , I want that select "listening on socket " whole the time while server is sending but select always return me 0 ....is there any solution maybe with different idea how to sending and receiving parallel?
int main (void) {
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
fd_set readfds;
FD_ZERO(&readfds);
// Create the socket
if((sd = socket (AF_INET, SOCK_DGRAM, 0)) < 0) {
printf("Server socket could not be created : %s\n",strerror(errno));
return 0;
}
// Non-blocking socket
fcntl(sd,F_SETFL,O_NONBLOCK);
FD_ZERO(&readfds);
FD_SET(sd,&readfds);
//Allow multiple applications to receive datagrams that are destined to the same local port number.
if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1){
printf("Setsockopt error: %s", strerror(errno));
return 1;
}
// Initialize the group sockaddr structure with a multicast address of 226.1.1.1 and port 5555.
memset((char *) &multiaddr, 0, sizeof(multiaddr));
multiaddr.sin_family = AF_INET;
multiaddr.sin_addr.s_addr = inet_addr(IP_GROUP);
multiaddr.sin_port = htons(PORT_NUM);
// Fill the structure udp_srv with informations like multicast address,port number and socket
strcpy(udp_srv.peer_address,inet_ntoa(multiaddr.sin_addr));
udp_srv.peer_port = multiaddr.sin_port;
udp_srv.udp_sd = sd;
if((fd = open("text.txt",O_RDONLY , 0777))== -1) {
printf("Error while opening txt file!\n",strerror(errno));
return 1;
} else {
while(1) {
sleep(1);
if((numRead = read(fd,tmp,512)) != 0) {
tmp[numRead]='\0';
strcpy(pack.buffer,tmp);
//function for sending data until EOF !
sent = data_sent(udp_srv,&pack);
} else {
sent = last_data_sent(udp_srv,&pack);
close(sd);
exit(1);
}
rv = select(sd + 1, &readfds, NULL, NULL, &tv);
if(rv > 0) {
// Create a new thread and call recvfrom in nack_processing function !
if(pthread_create(&cln_thread, NULL, nack_processing, (void *) &arg)){
printf("Pthrad create errorr\n",strerror(errno));
continue;
}
}
}
}
return 0;
}
Few suggestions.
change
if(rv == 1)toif(rv > 0)and provide some timeTry with that