gpt4 book ai didi

c - 带套接字的多用户 'guess a number'游戏,使用C

转载 作者:行者123 更新时间:2023-11-30 17:03:50 25 4
gpt4 key购买 nike

我在使用 C 语言的套接字完成程序时遇到问题。这是一个基本的“猜数字”游戏。问题是,一旦猜对了数字,客户端控制台就不会输出任何它应该输出的内容(“你赢了”和“继续猜测下一个数字”)。

来自 Client.c 的示例代码:

while (1) {
bzero(buffer,BUF_SIZE);
scanf("%s", &buffer);
send_line(sockfd, buffer);

if (strcmp(buffer, "quit") == 0)
break;

recv_line(sockfd, buffer);
printf("Server: %s\n", buffer);

if (strcmp("Bingo!", buffer) == 0) {
printf("You won!!");
recv_line(sockfd, buffer);
printf("Server: %s\n",buffer);
printf("Keep on guessing next number!\n");
}
}

来自Server.c的示例代码:

while (1) {
recv_line(new_fd, buffer);
printf("%s\n",buffer);
if (strcmp(buffer, "quit") == 0) {
printf("Client '%s' quit.\n", name);
break;
}
if (atoi(buffer) >lol){
send_line(new_fd,"number too big!");
}
if (atoi(buffer) <lol){
send_line(new_fd,"number too small!");
}
if (lol== atoi(buffer)){
send_line(new_fd, "Bingo!");
printf("Client '%s' guessed correctly!\n ", name);
printf("Enter new number fo user '%s'!\n", name);
scanf("%d", &lol);
send_line(new_fd, "New number generated!");
}
}
}

还有:

void send_line(int new_fd, char * buffer) {
int len = strlen(buffer);

if (send(new_fd, buffer, len, 0) == -1) {
perror("send");
exit(1);
}
}

void recv_line(int new_fd, char * buffer){
int len;

if ((len = recv(new_fd, buffer, BUF_SIZE, 0)) == -1){
perror("recv");
exit(1);
} else
buffer[len] = '\0';
}

当用户猜对后,我怎样才能让这个工作成功?

最佳答案

Strings "number too big" or "number too small" get printed out when needed and correctly, all that is failing is once the number is guessed correctly --> string "Bingo!" from Server.c goes to Client.c and then nothing happens until you put in a new number in Server.c

这正是客户端的编码方式:

if (strcmp("Bingo!", buffer) == 0) {
printf("You won!!");
recv_line(sockfd, buffer);
printf("Server: %s\n",buffer);
printf("Keep on guessing next number!\n");
}

stdio是行缓冲的。笼统地说,这意味着数据保留在内部缓冲区中,直到打印换行符。所以You won!! (没有换行符)字符串被打印,但不刷新,直到 printf("Server: %s\n",buffer)提供换行符。

更改printf("You won!!")printf("You won!!\n")或调用fflush(stdout)之后。

关于c - 带套接字的多用户 'guess a number'游戏,使用C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35999572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com