通常,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; } |