0

Hello guys,

i am making a simple test using select() for a future program i must do. What i'm trying to do is very simple, i have a client, and a server.

The client listens to both stdin and sockfd using select. The objective is as follows:

If i write something during select (FD_ISSET(stdin,&rset) is on), i will send to the server what i just wrote, inside a buffer.

If i only press enter, the program stops.

If i don't press anything, the client generates a random number, and sends it to the server.

The only thing the server does is send an "OK" message.

This is part of the code of the client:

FD_ZERO(&rset);
	FD_SET(fileno(stdin),&rset);
	FD_SET(sockfd,&rset);
	
	tv.tv_sec=timeout;
	tv.tv_usec=0;
	
		
	
	
	nready=select(sockfd+1,&rset,NULL,NULL,&tv);
	

	if (FD_ISSET(fileno(stdin), &rset)){ 
	
		if(fgets(buffer,MAXLINE,stdin)!=NULL){

			if(strcmp(buffer,"\n")==0){printf("Suministrador desconectado \n"); close(sockfd); exit(0);}
			buffer[MAXLINE]='\0';
			write(sockfd,buffer,sizeof(buffer));
			}

	        
	   
		}
			else{
		
		srand(rand());
		num2=rand()%10;
		sprintf(itoanum,"%d",num2);
		itoanum[2]='\0';
		

		write(sockfd,itoanum,sizeof(itoanum));
		
		
		
		}


	if (FD_ISSET(sockfd, &rset)){

	
		n=read(sockfd,buffer2,sizeof(buffer2));
		 
		buffer2[n]='\0';
		printf("> %s \n",buffer2);
		srand(rand());
		timeout=rand()%10;
		printf("%d \n",timeout);
	}






	}//fin bucle infinito

My problem is that, if i put "sockfd+1" as an argument in select() (which i think it's correct), the client enters a weird loop in which it only works as if nothing had been written, it's pretty strange to explain. However, if i just put "sockfd", stdin works perfectly, but of course, i can't receive anything from sockfd.

Does anyone know what is going wrong here? It's my first time using select(), so i may be making basic mistakes.


Thanks a lot in advance.

1
Contributor
1
Reply
4
Views
7 Years
Discussion Span
Last Post by rai32
0

I should note this correction:

1. for(;;)

It was pretty evident, but it may lead to confusion.

Please help me, i'm completely stuck here, and i've searched all over the Internet for a solution, to no avail.

Thanks

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.