如何清除套接字缓冲区中的先前数据?

时间:2016-03-31 20:28:57

标签: file sockets server

我将数据发送到我的服务器,该服务器将接收到的数据写回客户端,数据也存储在服务器上的文本文件中。

我遇到了这个问题:如果发送的消息长度小于以前发送的消息,则额外的字符会被添加到当前消息中。

例如,如果我发送"你好"首先,然后我发送" all",文件中存储的消息是:

hello
alllo

这是我的代码:

#include<stdio.h>
#include<string.h>    //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h>    //write

int main(int argc , char *argv[])
{
    int socket_desc , client_sock , c , read_size;
    struct sockaddr_in server , client;
    char client_message[2000];

    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 8888 );

    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        //print the error message
        perror("bind failed. Error");
        return 1;
    }
    puts("bind done");

    //Listen
    listen(socket_desc , 3);

    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);

    //accept connection from an incoming client
    client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&$
    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
    }
    puts("Connection accepted");

    //Receive a message from client
    while( (read_size = recv(client_sock , client_message , 2000 , 0)) > 0 )
    {
        //Send the message back to client
        write(client_sock , client_message , strlen(client_message));
        //append the received data at the end of the file
        FILE *f = fopen("data.txt", "a");
        if (f == NULL){
                printf("Error opening file!\n");
                exit(1);
        }
        char *text = client_message;
        fprintf(f, "%s\n", text);
        fclose(f);
        //clear socket
    }

    if(read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }

    return 0;
}

所以我认为我需要在写入文件后清除缓冲区,但我不知道该怎么做。非常感谢你的帮助!

1 个答案:

答案 0 :(得分:2)

常见问题。复制循环不正确。忽略接收长度,并假设数据填充缓冲区和/或以空值终止。

它应该看起来像这样:

while ((count = recv(source_sd, buffer, sizeof buffer, 0)) > 0)
{
    write(target_fd, buffer, count);
    // or
    fwrite(buffer, 1, count, target_file);
}

每次围绕循环打开和关闭文件都很糟糕。

与清除套接字缓冲区无关。循环后很明显。