C:如何清除socket上read()的缓冲区

时间:2013-04-21 21:31:06

标签: c string sockets buffer

我正在尝试从服务器接收数据,并且它第一次正常工作,但是当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);

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

1 个答案:

答案 0 :(得分:3)

在我看来,在您的代码中,您在打印之前删除了收到的数据 - 然后您将一个字符串传递给基本为空的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
    }