I created a chatroom with clients and a server and everything works. But I have a problem of printing. The problem is that the client can write his message and read the message from the other clients at the same time. So I used a thread to do both at the same time. It works but look at the example what the problem is :
Here I start writing my first messHere is the received message that interrupts my writingAnd here I continue writing
I don't know if it's clear : I start writing a message but I don't send it yet because it's not over but in the same time a message is received so it prints it after the beginning of my writing message and after I can continue writing.
Do you have an idea how to fix the problem ?
Here is the client code :
void getMessage(char* message) {
size_t ln = -1;
while (ln <= 0 || ln > MESSAGE_MAX-1) {
printf(">");
fgets(message, MESSAGE_MAX, stdin);
ln = strlen(message) - 1;
}
if (message[ln] == '\n')
message[ln] = '\0';
}
void *thread_message(void *arg)
{
char* message;
message = malloc (sizeof(char) * MESSAGE_MAX);
int* sockfd = (int*)arg;
while (1) {
getMessage(message);
if (send(*sockfd, message, strlen(message), 0) == -1){
perror("Client: send message");
}
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int sockfd, numbytes;
struct sockaddr_in their_addr;
// connector's address information
struct hostent *he;
char buf[MESSAGE_MAX + PSEUDO_MAX];
// ...
}
while (1) {
if ((numbytes=recv(sockfd, buf, MESSAGE_MAX+PSEUDO_MAX, 0)) == -1) {
perror("Client: recv");
return EXIT_FAILURE;
}
// ...
char* message;
message = malloc (sizeof(char) * MESSAGE_MAX);
// Here I launch the thread to write a message
pthread_t thread;
if (pthread_create(&thread, NULL, thread_message, &sockfd)) {
perror("pthread_create");
return EXIT_FAILURE;
}
}
// Here I print the messages I receive
else
{
buf[numbytes] = '\0';
printf("%s",buf);
}
}
close(sockfd);
return EXIT_SUCCESS;
}
Thanks for your help ! :)