theonastos
theonastos

Reputation: 25

String used in recv() does not printf as it should

I am trying to write a server-client program for practice but I'm having trouble with the the string I use in the recv() function.

void *recieve_handler(void *socket_desc){
int client_sock = *(int*)socket_desc;
int data_len;
char client_message[BUFFER_SIZE];

data_len = 1;

while (data_len > 0){
    data_len = recv(client_sock, client_message, BUFFER_SIZE, 0);
    client_message[data_len-1] = '\0';
    printf("%s\n", client_message);
    printf("ME:");
}
close(client_sock);

}

I would like after I receive the string from the client to print it and then print a label in the next line. The problem is whatever I try,I keep getting this outcome:

"1st message from client"
[buffer]

and then when the client sends another message it prints along with me ME: label in front of it.

ME: "2nd message from client"

I need to have the label printed with the 1st message.

Upvotes: 0

Views: 420

Answers (1)

AndersK
AndersK

Reputation: 36067

try to flush the stdout fflush(stdout); after printing ME:

e.g.

printf("%s\n", client_message);
printf("ME:");
fflush(stdout);

Upvotes: 1

Related Questions