You need to enable JavaScript to run this app. C套接字实现文件下载时10MB以上大文件传输损坏问题
优惠活动
大模型
产品
解决方案
定价
更多

C套接字实现文件下载时10MB以上大文件传输损坏问题

C语言套接字大文件传输异常排查与修复

现有实现逻辑

  • 客户端逻辑:先读取待发送文件总大小,每次按1024字节为单位循环发送完整数据块,最后发送不足1024字节的尾部数据;
  • 服务器端逻辑:接收所有传输数据后,以追加模式写入运行时创建的目标文件。

客户端代码

char localfilename[260];
// 从命令缓冲区提取待发送文件名,例如下载命令"download hi.txt hello.txt"会提取"hi.txt"
if (get_string_between_spaces(localfilename, buffer, sizeof(buffer), 1, 2) == -1)
{
    send_message(sock, "error", sizeof("error")); // 封装的send()工具函数
    goto jump;
}

FILE *pLOCALFILE;
pLOCALFILE = fopen(localfilename, "rb");
if (!pLOCALFILE)
{
    send_message(sock, "File not found on target system.Exiting..\n", sizeof("File not found on target system.Exiting..\n"));
    goto jump;
}
else
{
    send_message(sock, "File found target system going on...\n", sizeof("File found target system going on...\n"));
}

int size_of_file = get_file_size(pLOCALFILE); // 返回文件总大小
int remainder = size_of_file % 1024; 
int quotient = size_of_file / 1024;

// 先发送文件大小、剩余字节数、整块数给服务器
send_integer(sock, size_of_file);
send_integer(sock, remainder);
send_integer(sock, quotient);

// 循环发送所有1024字节整块
for (int i = 0; i < quotient; i++)
{
    fread(container, 1, 1024, pLOCALFILE);
    send(sock, container, sizeof(container), 0);
    memset(container, 0, sizeof(container));
}

// 发送不足1024字节的尾部数据,若quotient为0则直接走这步完成传输
fread(container, 1, remainder, pLOCALFILE);
send(sock, container, remainder, 0);
memset(container, 0, sizeof(container));
fclose(pLOCALFILE);

服务器端代码

char filename[260];
// 从命令缓冲区提取目标保存文件名,例如下载命令"download hi.txt hello.txt"会提取"hello.txt"
get_string_between_spaces(filename, buffer, sizeof(buffer), 2, 3);

FILE *pFILETOWRITE;
pFILETOWRITE = fopen(filename, "ab"); // 以字节追加模式打开目标文件
if (pFILETOWRITE)
{
    printf("The file %s has been opened.\n", filename);
}
else
{
    printf("Couldn't open the %s file.\n", filename);
    goto jump;
}
            
// 接收客户端的文件状态反馈
recv(client_socket, receive_response, sizeof(receive_response), 0);
printf("%s\n", receive_response);

char containerOFmode[1024];
bzero(containerOFmode, sizeof(containerOFmode));
// 接收客户端发送的文件元信息:总大小、剩余字节数、整块数
int size_of_client_file = recv_integer(client_socket);
int remainder = recv_integer(client_socket);
int quotient= recv_integer(client_socket);
int bytes_transferred = 0;
printf("%d bytes are to be transferred.\n", size_of_client_file);
printf("The remainder is %d\n", remainder);
printf("The cat is %d\n", quotient); // 原代码拼写错误,实际为打印整块数

// 循环接收所有1024字节整块
for (int i = 0; i < quotient; i++)
{
    recv(client_socket, containerOFmode, sizeof(containerOFmode), 0);
    bytes_transferred += sizeof(containerOFmode);
    fwrite(containerOFmode, sizeof(char), sizeof(containerOFmode), pFILETOWRITE);
    printf("%s\n", containerOFmode);
    printf("The size of this send was:%d\n", sizeof(containerOFmode));
    printf("Bytes transferred so far:%d\n", bytes_transferred);
    bzero(containerOFmode, sizeof(containerOFmode));
}

// 接收尾部剩余数据
recv(client_socket, containerOFmode, remainder. 0); // 原代码语法错误,参数分隔符误写为点
bytes_transferred += remainder;
fwrite(containerOFmode, sizeof(char), remainder, pFILETOWRITE);
printf("%s\n", containerOFmode);
printf("The size of this send was:%d\n", remainder);
printf("Bytes transferred so far:%d\n", bytes_transferred);
bzero(containerOFmode, sizeof(containerOFmode));

fclose(pFILETOWRITE);
goto jump;

异常现象

传输10MB以内的文件功能正常,传输超过10MB的视频、可执行文件等大文件时,接收端生成的文件会损坏无法正常使用。

核心问题根因

这个问题的本质是未遵循TCP套接字的流式特性,直接使用裸recv()/send()调用、未处理实际读写长度:

  • TCP是面向字节流的协议,send()和recv()的返回值为实际发送/接收的字节数,并非传入的请求长度。例如调用recv(sock, buf, 1024, 0)时,可能仅返回500字节,剩余524字节仍在内核缓冲区;如果直接将buf按1024字节写入文件,会混入前一次缓冲区的残留脏数据,同时缺失的524字节会被下一次循环误判为新的整块数据,造成全局数据错位。
  • 小文件整体传输量小,TCP缓冲区可一次性承载,短读/短发的触发概率极低,因此不会暴露问题;大文件传输过程中会频繁出现短读/短发,累积的错位错误会直接导致文件损坏。
  • 附带问题:
    • 未判断recv()返回值为-1(调用错误)或0(连接异常断开)的场景;
    • 服务器端存在语法错误,尾部数据接收的recv参数分隔符误写为.而非逗号;
    • 服务器端以ab追加模式打开文件,重复下载同一文件时会残留旧数据,导致文件内容混杂;
    • 直接将二进制文件内容按C字符串格式用printf("%s\n", ...)输出,二进制数据中无末尾\0时会触发未定义行为。

修复方案

1. 封装可靠的全量读写函数

TCP套接字下必须循环读写,直到取到/发完指定长度的数据:

#include <unistd.h>
#include <errno.h>

// 从套接字读取指定长度的数据,返回实际读取的字节数,0表示连接断开,-1表示调用错误
int readn(int fd, void *buf, size_t len)
{
    size_t total = 0;
    ssize_t nread;
    char *ptr = (char*)buf;
    while (total < len)
    {
        nread = recv(fd, ptr + total, len - total, 0);
        if (nread == -1)
        {
            if (errno == EINTR) continue; // 被信号中断则重试
            return -1;
        }
        else if (nread == 0)
        {
            return total; // 连接提前断开,返回已读取的字节数
        }
        total += nread;
    }
    return total;
}

// 向套接字写入指定长度的数据,返回实际写入的字节数,0表示连接断开,-1表示调用错误
int writen(int fd, const void *buf, size_t len)
{
    size_t total = 0;
    ssize_t nwrite;
    const char *ptr = (const char*)buf;
    while (total < len)
    {
        nwrite = send(fd, ptr + total, len - total, 0);
        if (nwrite == -1)
        {
            if (errno == EINTR) continue;
            return -1;
        }
        total += nwrite;
    }
    return total;
}

2. 替换原有裸读写调用

将客户端的sock发送逻辑、服务器端的sock接收逻辑全部替换为writen/readn调用,确保每次完整读写指定长度的数据:

  • 客户端发送1024字节整块的示例:
for (int i = 0; i < quotient; i++)
{
    size_t fread_cnt = fread(container, 1, 1024, pLOCALFILE);
    if (fread_cnt != 1024) break; // 读取文件异常则中止传输
    if (writen(sock, container, 1024) != 1024) break; // 发送失败则中止
    memset(container, 0, sizeof(container));
}
  • 服务器端接收1024字节整块的示例:
for (int i = 0; i < quotient; i++)
{
    ssize_t nrecv = readn(client_socket, containerOFmode, sizeof(containerOFmode));
    if (nrecv != sizeof(containerOFmode)) break; // 接收失败/连接断开则中止
    bytes_transferred += nrecv;
    fwrite(containerOFmode, 1, nrecv, pFILETOWRITE);
    bzero(containerOFmode, sizeof(containerOFmode));
}

3. 修正细节问题

  • 将服务器端打开文件的模式从ab(追加写)改为wb(覆盖写),避免重复下载时旧数据残留;
  • 修正服务器端尾部接收的语法错误:把recv(client_socket, containerOFmode, remainder. 0)中的.改为逗号;
  • 移除对二进制内容的printf("%s\n", ...)输出,如需调试可直接打印实际传输的字节数;
  • 所有套接字、文件操作调用增加返回值判断,遇到错误及时中止传输,清理文件句柄、套接字资源。

内容的提问来源于stack exchange,提问作者Fine Baby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 20:36:00