无法从客户端读取数据到服务器

时间:2016-01-24 05:00:04

标签: c

我无法从服务器/客户端程序中读取客户端的值。用户应该在客户端进入一个国家,服务器应该处理该值,然后返回与该国家相关的信息(资本,货币)。

对于我的程序,服务器能够第一次返回正确的数据。例如,在中国的用户密钥,服务器将返回首都作为北京等。

然而,当用户输入例如'德国'第二次,服务器根本不返回任何数据。

希望你们能够识别我的代码中的错误。提前谢谢!

提前致谢!

1 个答案:

答案 0 :(得分:0)

客户端方面,打印收到的答案后,您正在关闭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;
 }
相关问题