hi i am trying to write a simple client server chat program.
the code of server program is:
the code in bold is looping the reads and writes so that both server and client can continuously send message to each other one after another
but the problem is
after connecting to the server using another client program,
after first iteration, the loop goes uncontrollable, that is it doesn't wait for scanf, but just goes on looping infinitely
the code of server program is:
Code:
#define PORT 9999 int main() { struct sockaddr_in server_addr,client_addr; int sockfd, newsockfd, clientlen,reuse=1; char buf[30],buf1[30]; if ((sockfd=socket(AF_INET, SOCK_STREAM, 0))==-1) { perror("socket"); exit(1); } setsockopt(sockfd, SOL_PACKET, SO_REUSEADDR, &reuse, sizeof (int)); server_addr.sin_family=AF_INET; server_addr.sin_port=htons(PORT); server_addr.sin_addr.s_addr=INADDR_ANY; if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof server_addr)==-1) { perror("bind"); exit(1); } if (listen(sockfd,0)==-1) { perror("listen"); exit(1); } clientlen=sizeof client_addr; if ((newsockfd=accept(sockfd,(struct sockaddr *)&client_addr, &clientlen))==-1) { perror("accept"); exit(1); } close(sockfd); [B]while(1){ read(newsockfd, buf, sizeof buf); printf("client: %s",buf); printf("\nYou: "); //fscanf(stdin,"%[^\n]",buf1); gets(buf1); write(newsockfd, buf1, sizeof (buf1)); }[/B] close(newsockfd); return 0; }
but the problem is
after connecting to the server using another client program,
after first iteration, the loop goes uncontrollable, that is it doesn't wait for scanf, but just goes on looping infinitely
Comment