我创建了一个带有客户端和服务器的聊天室,一切正常。但是我有一个打印问题。问题是客户端可以同时写入他的消息并读取来自其他客户端的消息。所以我用一个线程同时做这两件事。它有效,但看看这个例子问题是什么:
Here I start writing my first messHere is the received message that interrupts my writingAnd here I continue writing
我不知道是否清楚:我开始写一条消息但我还没有发送它,因为它还没有结束但同时收到一条消息所以它在我写消息开始后打印它并且在我可以继续写作之后。
你知道如何解决这个问题吗?
这是客户端代码:
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;
}
感谢您的帮助! :)
最佳答案
解决问题的一种方法:可能使用来自 ncurses
的 getch
.将您已经输入的内容保存到缓冲区中。并在终端的不同行显示来自其他客户端的消息和您的输入。
注意:我以前从未使用过 libncurses,但是当我看到 examples 时ncurses
,我知道它可以满足聊天程序的需要。希望对您有所帮助。
关于c - 客户端如何使用套接字同时发送和接收消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27504701/