HTTP协议中的"Transfer-Encoding: chunked"

   通常,HTTP协议中使用Content-Length这个头来告知数据的长度。然后,在数据下行的过程中,Content-Length的方式要预先在服务器中缓存所有数据,然后所有数据再一股脑儿地发给客户端。
    如果要一边产生数据,一边发给客户端,WEB 服务器就需要使用"Transfer-Encoding: chunked"这样的方式来代替Content-Length。

    "Transfer-Encoding: chunked"是这样编码的:
HTTP头
/r/n
/r/n      --连续的两个/r/n之后就是HTTP体了
16进制值代表的数据长度
/r/n
上面所指的数据长度
/r/n    --每段数据结束后,以/r/n标识

16进制代表的第二段数据
/r/n
XX长度的数据
/r/n

………… (反复通过这样的方式表示每次传输的数据长度)

0      --数据结束部分用0表示,然后是连续的两个/r/n
/r/n
/r/n

      下面的代码演示和如何解析"Transfer-Encoding: chunked"的数据:
//test_chunked.cpp
#include <stdio.h>
#include <string.h>

int Hex2Int(const char* str)
{
    int nResult = 0;
    while (*str!='/0')
    {
        switch (*str)
        {
        case '0'...'9':
            nResult = nResult*16 + *str-'0';
            break;
        case 'a'...'f':
            nResult = nResult*16 + *str-'a'+10;
            break;
        case 'A'...'F':
            nResult = nResult*16 + *str-'A'+10;
            break;
        default:
            return -1;
            break;
        }
        str++;
    }
    return nResult;
}

#define COPY_STRING(dst, src, src_len) do{memcpy((dst), (src), (src_len)); dst[(src_len)]='/0';}while(0);

void test(const char* file)
{
    //
    const int BUFFER_SIZE = 1024*10;
    char* buf = new char[BUFFER_SIZE];
    FILE* fp = fopen(file, "rb");
    if (NULL==fp)
    {
        printf("open file error/n");
        return;
    }
    int nLen = fread(buf, 1, BUFFER_SIZE, fp);
    fclose(fp);
    fp = NULL;
    buf[nLen] = '/0';
    //
    char* pBody = strstr(buf, "/r/n/r/n");
    if (NULL==pBody)
    {
        return;
    }
    pBody += 4;
    FILE* fDst = fopen("result.txt.gz", "ab");
    //下面开始解析
    int nBytes;
    char* pStart = pBody;
    char* pTemp;
    char temp[10];
    do
    {
        pTemp = strchr(pStart, '/r');
        if (NULL==pTemp)
        {
            printf("格式错误!/n");
            break;
        }
        nLen = pTemp-pStart;
        COPY_STRING(temp, pStart, nLen);
        nBytes = Hex2Int(temp);
        pStart = pTemp + 2;
        //下面写入到另一个文件
        if (nBytes>0)
        {
            if (nBytes!=fwrite(pStart, 1, nBytes, fDst))
            {
                printf("write error!/n");
                break;
            }
            pStart += nBytes + 2;
        }
    } while(nBytes>0);
    fclose(fDst);
    fDst = NULL;
    delete[] buf;
    buf = NULL;
}

int main()
{
    test("chunked.txt");
    return 1;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值