分块传输编码

时间:2013-12-15 08:15:38

标签: visual-c++ http.sys

我开发了一个Http服务器, 我的响应代码摘要是:

PHTTP_DATA_CHUNK p = new HTTP_DATA_CHUNK[count];
for (int i = 0; i<count; i++)
{
  p[i].DataChunkType = HttpDataChunkFromMemory;
  p[i].FromMemory.pBuffer = "dfdff"; 
  p[i].FromMemory.BufferLength = 5;
}

HTTP_RESPONSE response;  
ZeroMemory(&response,sizeof(HTTP_RESPONSE));  
PCSTR Reason="OK";  
response.StatusCode=200;  
response.pReason=Reason;  
response.ReasonLength=strlen(Reason);  
ADD_KNOWN_HEADER(response, HttpHeaderContentType, "text/html");
ADD_KNOWN_HEADER(response, HttpHeaderConnection, "keep-alive");
ADD_KNOWN_HEADER(response, HttpHeaderTransferEncoding, "chunked");
ADD_KNOWN_HEADER(response, HttpHeaderContentLength, chLen);

response.EntityChunkCount = count;
response.pEntityChunks=p;
ULONG BytesSent;
ULONG result = HttpSendHttpResponse(ReqQueueHandle, HttpRequest->RequestId, 
                                            0, &response, NULL,&BytesSent, NULL, 
                                            0,NULL,NULL, NULL);

但结果是87! 现在,如果我删除这行代码:

ADD_KNOWN_HEADER(response, HttpHeaderTransferEncoding, "chunked");

结果是0,我的回复会发送给客户。 我如何利用Chunked transfer encoding

1 个答案:

答案 0 :(得分:1)

当我按以下方式重新排列代码时,响应正确发送:

response.EntityChunkCount = 0;
response.pEntityChunks=0;
ULONG BytesSent;
ULONG result = HttpSendHttpResponse(ReqQueueHandle, HttpRequest->requestId,
                                            0, &response, NULL,&BytesSent, NULL,
                                            0,NULL,NULL, NULL);
for (/*buffers */)
{
    PHTTP_DATA_CHUNK chunk;
    chunk.DataChunkType = HttpDataChunkFromMemory;
    chunk.FromMemory.pBuffer = buffer[i]; //--- "bufferLen\r\n .... \r\n"
    chunk.FromMemory.BufferLength = len[i];
    HttpSendResponseEntityBody(ReqQueueHandle, HttpRequest->requestId, 
                                 HTT_SEND_RESPONSE_FLAG_MORE_DATA, 1, &chunk, 0
                                 NULL, 0, NULL, NULL);
}

PHTTP_DATA_CHUNK chunkEnd;
chunkEnd.DataChunkType = HttpDataChunkFromMemory;
chunkEnd.FromMemory.pBuffer = "\r\n0\r\n";
chunkEnd.FromMemory.BufferLength = 5;
HttpSendResponseEntityBody(ReqQueueHandle, HttpRequest->requestId,
                                 HTT_SEND_RESPONSE_FLAG_DISCONNECT, 1, &chunkEnd, 0
                                 NULL, 0, NULL, NULL);