【问题标题】:TCP send a file data from client to server problem: different checksum on fileTCP 从客户端向服务器发送文件数据问题:文件校验和不同
【发布时间】:2022-12-07 02:05:13
【问题描述】:

我尝试通过 TCP ipv4 连接套接字传输大约 100MB 的数据大小。

我在发送之前计算客户端中的 CheckSum 以查看校验和是多少。

将数据文件发送到服务器并且服务器将其写入新文件后,我再次计算校验和,我可以看到不同之处。

我认为可能与我的发送和接收功能有关。

CLIENT 中使用的 Sender 函数:

void send_file(FILE *fp, int sockfd) {
    int n;
    char data[SIZE] = {0};

    while (fgets(data, SIZE, fp) != NULL) {
        if (send(sockfd, data, sizeof(data), 0) == -1) {
            perror("[-]Error in sending file.");
            exit(1);
        }
        bzero(data, SIZE);
    }
}

Writer函数在SERVER中的使用:

    void write_file(int sockfd, char *filename) {
    int n;
    FILE *fp;
    //char *filename = "new_data.txt";
    char buffer[SIZE];

    fp = fopen(filename, "w");
    while (1) {
        n = recv(sockfd, buffer, SIZE, 0);
        if (n <= 0) {
            break;
            return;
        }
        fprintf(fp, "%s", buffer);
        bzero(buffer, SIZE);
    }
}

【问题讨论】:

  • 您应该使用 fread() 和 fwrite() 而不是 fgets() 和 fprintf()。并检查 fread() 的结果,它会告诉您读取了多少字节,因此您应该只发送那么多字节。

标签: c file sockets tcp


【解决方案1】:

fgets() 和 fprintf() 用于读写以零结尾的字符串,而不是任意二进制数据。 fread() 和 fwrite() 是你的朋友。就像是:

客户:

#define CHUNK_SIZE 1024
char buffer[CHUNK_SIZE];

while ((num_bytes = fread(buffer, 1, CHUNK_SIZE, fp)) > 0)
{
    send(sockfd, buffer, num_bytes, 0);
}

服务器:

// Same chunk size and buffer as above

while ((num_bytes = recv(sock, buffer, CHUNK_SIZE, 0)) > 0)
{
    fwrite(buffer, 1, num_bytes, fp);
}

从技术上讲,fwrite() 可以写入比您要求的更少的字节,您确实应该循环直到写入所有字节,但您通常不会在现代 PC 上看到它。

对于二进制文件,您还应该在技术上使用“rb”和“wb”模式打开文件。

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2018-09-24
    • 1970-01-01
    • 2017-07-10
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多