c - How can client send and receive messages at the same time with sockets? -
i created chatroom clients , server , works. have problem of printing. problem client can write message , read message other clients @ same time. used thread both @ same time. works @ example problem :
here start writing first messhere received message interrupts writingand here continue writing
i don't know if it's clear : start writing message don't send yet because it's not on in same time message received prints after beginning of writing message , after can continue writing.
do have idea how fix problem ?
here 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 launch thread write message pthread_t thread; if (pthread_create(&thread, null, thread_message, &sockfd)) { perror("pthread_create"); return exit_failure; } } // here print messages receive else { buf[numbytes] = '\0'; printf("%s",buf); } } close(sockfd); return exit_success; }
thanks ! :)
one way solve problem: maybe using getch
ncurses
. save have inputted buffer. , display messages other clients , input in different line of terminal.
note: never used libncurses before, when see examples of ncurses
, know can fulfill need of chat program. hope helps.
Comments
Post a Comment