按照HTTP的协议, 当服务器知道要发送的Content的长度时, 在HTTP头就会生成 Content-Length:xxx 这样的长度信息,
但是有时候我们即使知道长度, 也希望用Chunked模式发送内容, 那要怎么使用?
经过查看libmicrohttpd的源码里有这个关键函数:
static int try_ready_chunked_body (struct MHD_Connection *connection)
这是chunk模式下专门处理chunk的,仔细看懂这个函数的代码就知道怎么处理chunk模式了。
应用层使用方法如下 :
response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN/*stbuf.st_size*/, 32 * 1024, &file_reader, file, &free_callback);
if (response == NULL)
{
fclose (file);
return MHD_NO;
}
ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
MHD_add_response_header (response, MHD_HTTP_HEADER_TRANSFER_ENCODING, "chunked");
MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION, "Keep-Alive");
MHD_destroy_response (response);
回调函数file_reader要如下使用 :
static ssize_t file_reader (void *cls, uint64_t pos, char *buf, size_t max)
{
FILE *file = (FILE*)cls;
(void) fseek (file, pos, SEEK_SET);
int n = fread (buf, 1, max, file);
if (0 == n)
return MHD_CONTENT_READER_END_OF_STREAM;
if (n < 0)
return MHD_CONTENT_READER_END_WITH_ERROR;
return n;
}
这样就可以了。