我遇到了microhttpd服务器的问题,我自己无法解决。我正在从SQLite数据库中读取一些数据,我正在尝试以类似json的格式对其进行格式化并将其发送给客户端。
rc = sqlite3_exec(db, sql, callback, (void*)connection, &zErrMsg);
回调:
int callback(void *connection, int argc, char **argv, char **azColName)
{
int i;
for(i=0; i<argc; i++)
{
char *display_page=malloc(1000); /* Size will be changed to fit, this is for testing.*/
/* azColName = Name of the column in database */
/* argv = value of the column*/
sprintf(display_page, "{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":\"%s\"}\n",
azColName[i], argv[i] ? argv[i] : "NULL",
azColName[i+1], argv[i+1] ? argv[i+1] : "NULL",
azColName[i+2], argv[i+2] ? argv[i+2] : "NULL" );
printf("disp page= %s\n", display_page);
if (!send_page(connection, display_page))
printf("failed\n");
free(display_page);
i+=2;
}
return 0;
}
发送页面:
send_page (struct MHD_Connection *connection, char *page)
{
int ret;
struct MHD_Response *response;
response =
MHD_create_response_from_buffer (strlen (page), (void *) page,
MHD_RESPMEM_PERSISTENT);
if (!response)
return MHD_NO;
ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
printf("ret = %d\n", ret);
MHD_destroy_response (response);
return ret;
}
输出:
disp page= {"SUBJECT":"Todo1","DESCRIPTION":"asdf","URGENCY":"asdf"}
ret = 1
disp page= {"SUBJECT":"Todo2","DESCRIPTION":"NULL","URGENCY":"fdsa"}
ret = 0
failed
disp page= {"SUBJECT":"Todo3","DESCRIPTION":"qwer","URGENCY":"qwer"}
ret = 0
failed
似乎问题出现在MHD_queue_response的某个地方,但我不知道为什么因为我是网络新手。任何帮助将不胜感激。
答案 0 :(得分:0)
我认为问题来自MHD_create_response_from_buffer
函数调用:
缓冲区的内存管理选项;如果缓冲区是静态/全局内存,则使用MHD_RESPMEM_PERSISTENT,如果缓冲区是堆分配的,则使用MHD_RESPMEM_MUST_FREE,如果缓冲区位于临时内存(即堆栈中),则必须由MHD和MHD_RESPMEM_MUST_COPY释放,并且必须由MHD复制;
当您将响应排入队列时,您应该复制数据(MHD_RESPMEM_MUST_COPY
而不是MHD_RESPMEM_PERSISTENT
):
response =
MHD_create_response_from_buffer (strlen (page), (void *) page,
MHD_RESPMEM_MUST_COPY);
因为在您释放页面之前可能不会发送回复。
此外,一个http查询只会出现一个响应。所以你必须构建一个更大的页面来同时发送所有内容:
int callback(void *connection, int argc, char **argv, char **azColName)
{
int i;
char *display_page = malloc(10000); /* Size will be changed to fit, this is for testing.*/
for(i=0; i<argc; i+=)
{
char subpage[256] = "";
sprintf(subpage, "{\"%s\":\"%s\",\"%s\":\"%s\",\"%s\":\"%s\"}\n",
azColName[i], argv[i] ? argv[i] : "NULL",
azColName[i+1], argv[i+1] ? argv[i+1] : "NULL",
azColName[i+2], argv[i+2] ? argv[i+2] : "NULL" );
printf("subpage= %s\n", subpage);
strncat(display_page, subpage, sizeof subpage-1);
}
if (!send_page(connection, display_page))
printf("failed\n");
free(display_page);
return 0;
}