'Why isn't this c client able to read data sent by this c server if the latter calls the write system call twice?

How come this client is only able to read data sent from the first server write system call ? It correctly reads the data sent by the first write, but not with the second one...

Here's the client :

#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define PORT 1025
#define SA struct sockaddr

int main(){


int sockfd;
struct sockaddr_in servaddr, cli;
//CREATE SOCKET
sockfd = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
    if (sockfd == -1) {
        printf("socket creation failed...\n");
        exit(0);
    }
bzero(&servaddr, sizeof(servaddr));
   
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servaddr.sin_port = htons(PORT);

if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) {
        printf("connection with the server failed...\n");
        exit(0);
    }

char buff[1024];
while( (read(sockfd, buff,sizeof(buff))) > 0){
printf("%s\n",buff);
}

close(sockfd);

return 0;

}


And here is the server :

#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#define SA struct sockaddr
#define PORT 1025


int main(){


 int sockfd, connfd;
 unsigned int len;
 struct sockaddr_in servaddr, cli;

//SOCKET CREATION
sockfd = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
if (sockfd == -1) {
        printf("socket creation failed...\n");
        exit(0);
    }

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr =htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
//BIND
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
        printf("socket bind failed...\n");
        exit(0);
    }
//LISTEN
if ((listen(sockfd, 5)) != 0) {
        printf("Listen failed...\n");
        exit(0);
    }

for(;;){

len = sizeof(cli);

connfd = accept(sockfd, (SA*)&cli, &len);


if (connfd < 0) {
        printf("server accept failed...\n");
        exit(0);
    }
char buff[]="Hi";
char buff2[]="More data sent..\n";

write(connfd,buff,sizeof(buff)); //work
write(connfd,buff2,sizeof(buff2)); //doesn't work


close(connfd);
}


return 0;

}


I also noticed it works if I put the second write inside a loop that requires a certain amount of time. For example :


long max=0;
while(max<1000000000){

//second write works
write(......);

}

Could someone give an explanation of why write behaves like that and what's going on under the hood ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source