I am trying client server code with Select call. But once i send from client to server, server continously reads from the buffer send by client even though client is not sending anything after Ist packet.Where i am doing wrong ?
Below is snippet of code:
fd_set readSet,master_list_read;
FD_ZERO(&master_list_read);
FD_SET(STDIN, &master_list_read);//stdin manually trigger reading
FD_SET(sockfd, &master_list_read);//tcp socket
struct timeval tv;
int retval;
tv.tv_sec = 10;
tv.tv_usec = 0;
while(1)
{
bool idle=false;
char *buffer=NULL;
int n;
tv.tv_sec = 10;
readSet=master_list_read;
retval = select(sockfd+1, &readSet, NULL, NULL,&tv);
if (retval == -1)
{
perror("Error in select\n");
exit(4);
}
else if(retval==0)
{
printf("*********SEND SUCCESSFUL******\n");
}
else
{
if(FD_ISSET(0, &readSet))
{
bzero(buf,256);
fgets(buf,256,stdin);
if (send(sockfd, buffer,n, 0) == -1) perror("error in sending MSG to server\n");
}
else if (FD_ISSET(sockfd, &readSet)) // receives data from server,print it on StdOutput
{
bzero(buf,256);
int nbytes = recv(sockfd, buf, 256,0);
if(nbytes<=0)
{
perror("recv error from server \n");
exit(0);
}
}
} //END OF ELSE
} //end of while
close(sockfd);
return 0;
The select() call in your while(1) loop leaves the readSet unchanged. This means that later the FD_ISSET() check succeeds.
The solution is simple: clear the fd_set's on every iteration:
FD_ZERO(&master_list_read);
FD_SET(STDIN, &master_list_read);
FD_SET(sockfd, &master_list_read);
// only now the select() returns what you need
retval = select(sockfd+1, &master_list_read, NULL, NULL,&tv);
// use the master_list_read later
Simply copying the fd_set does not solve the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With