There is a simple Client-Server program.
- The server is started $./server 5000
- The client is also connected to server.. $./client 127.0.0.1 5000
- The client enters a string
- Client has the message "I got your message" displayed on his terminal & server displays the entered string by the client
The issue is that when I run client by doing $./client 127.0.0.1 5000. I get this in server side terminal.
Before Listen
After Listen
Before accept
After accept
Before read
Then only when I enter the message on client screen and then press enter. I get this displayed..
Here is the message: This is a message
Why is that the code goes into wait state before read() call.. Shouldnt it just read nothing and return 0..
I am wrong somewhere conceptually. Pls help me out..
Relevant code of Client:-
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
printf("%d\n",n);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
Relevant Server code:-
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
printf("Before Listen ");
listen(sockfd,5);
printf("After Listen ");
clilen = sizeof(cli_addr);
printf("Before accept ");
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
printf("After accept");
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,256);
printf("Before read");
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0) error("ERROR writing to socket");