4

我正在尝试从服务器接收数据,它第一次工作正常,但随着 read() 不断循环,它也会存储它之前读取的旧值。这是我到目前为止所拥有的。

        char receive[50];

        if((he = gethostbyname(servername)) == NULL ) {

            perror(strcat("Cannot find server named:", servername));
            exit(0);
        }

        he = gethostbyname("localhost");
        localIP = inet_ntoa(*(struct in_addr *)*he->h_addr_list);
        client_sock_desc = socket(AF_INET, SOCK_STREAM, 0);
        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = inet_addr(localIP);
        server_addr.sin_port = htons(serverport);
        len = sizeof(server_addr);
        if(connect(client_sock_desc, (struct sockaddr *)&server_addr,len) == -1) {
            perror("Client failed to connect");
            exit(0);
        }

        strcpy(buf, "CLIENT/REQUEST\n");
        send(client_sock_desc, buf, strlen(buf), 0);
        //send actual function request

        //put a space before \n char to make it easier for the server
        for(i = 0; i < sizeof(wholeRequest); i++) {
            if(wholeRequest[i] == '\n') {
                wholeRequest[i] = ' ';
                wholeRequest[i+1] = '\n';
                break;
            }
        }

        while(read(client_sock_desc, receive, sizeof(receive)) > 0) {
            strcpy(receive, ""); //attempt to erase all old values
            printf(receive);
            fflush(stdout);
        }
        close(client_sock_desc);

当服务器发送一次数据并关闭套接字时,它可以完美地工作。但后来我让客户端再次打开套接字,向服务器发送数据,服务器将再次向客户端发送数据并关闭套接字。客户端将再次尝试读取服务器发送的数据,但这一次它用新信息和部分旧信息填充接收

4

1 回答 1

5

在我看来,在您的代码中,您在打印之前删除了接收到的数据 - 然后您将一个字符串传递给该字符串,该字符串printf基本上是空的,我不确定它是做什么printf的(因为它是空的格式化字符串)。

尝试这个:

int nread;
while((nread = read(client_sock_desc, receive, sizeof(receive)-1)) > 0) {
        receive[nread]='\0';    // explicit null termination: updated based on comments
        printf("%s\n",receive); // print the current receive buffer with a newline
        fflush(stdout);         // make sure everything makes it to the output
        receive[0]='\0';        // clear the buffer : I am 99% sure this is not needed now
    }
于 2013-04-21T21:38:13.907 回答