gpt4 book ai didi

c - 从客户端读取数据到服务器时遇到问题

转载 作者:行者123 更新时间:2023-11-30 19:40:45 25 4
gpt4 key购买 nike

我在从服务器/客户端程序读取客户端的值时遇到问题。用户在客户端输入一个国家,服务器处理该值,然后返回与该国家相关的信息(资本、货币)。

对于我的程序,服务器第一次能够返回正确的数据。例如,用户输入“China”,服务器将返回大写字母“beijing”等。

但是,当用户第二次输入“德国”时,服务器根本不会返回任何数据。

希望你们能找出我的代码中的错误。提前致谢!

提前致谢!

最佳答案

客户端端,打印收到的答案后,您将关闭clientFd,并且不会尝试重新连接以供进一步使用。事实上,第二次write是在一个关闭的文件描述符上进行的。一种解决方案是这样的:

while (1) {
/* Create a socket, bidirectional, default protocol */
clientFd = socket(AF_LOCAL, SOCK_STREAM, DEFAULT_PROTOCOL);

do { /* Loop until a connection is made with the server */
result = connect(clientFd, serverSockAddrPtr, serverLen);
printf("Attempting to connect...\n");
if (result == -1) sleep(1); /* Wait and then try again */
} while (result == -1);

char country[300];

printf("%s \n", " ");
printf("Please enter country > ");
fflush(stdout);
fgets(country, sizeof(country), stdin);
printf("%s \n", " ");

if (0 == strcmp(country, "end\n")) {
printf("Thank you for using country services\n");
exit(0);
} else {
write(clientFd, country, strlen(country));
parse(clientFd);
}

close(clientFd);
printf("%d\n", clientFd);
clientFd = 0;
}

关于c - 从客户端读取数据到服务器时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972420/

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