嗨,我正在使用 mongoose 服务器开发嵌入式服务器。我有来自Mongoose Doc的以下代码。
#include <string.h>
#include "mongoose.h"
static int event_handler(struct mg_connection *conn, enum mg_event ev) {
if (ev == MG_AUTH) {
return MG_TRUE; // Authorize all requests
} else if (ev == MG_REQUEST && !strcmp(conn->uri, "/hello")) {
mg_printf_data(conn, "%s", "Hello world");
return MG_TRUE; // Mark as processed
} else {
return MG_FALSE; // Rest of the events are not processed
}
}
int main(void) {
struct mg_server *server = mg_create_server(NULL, event_handler);
//mg_set_option(server, "document_root", ".");
mg_set_option(server, "listening_port", "8080");
for (;;) {
mg_poll_server(server, 1000); // Infinite loop, Ctrl-C to stop
}
mg_destroy_server(&server);
return 0;
}
此代码完美运行。发送“Hello World”后,MG_POLL 停止。和 chrome 显示加载完成。但是当我尝试通过替换 mg_printf 来发送错误代码时
mg_printf(conn,"HTTP/1.1 400 Bad Request\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\nCache-control: private\r\n"
"Server: lighttpd/1.4.26\r\n\r\n"
"<html><body>"
"<h2>OOPS !!!!</h2>"
"<p>Check the url... Url is malformed</p>"
"</body></html>");
轮询永远不会停止,并且在 chrome 中它的节目仍在加载。发送自定义错误代码是否需要额外的东西?
添加后
void mg_send_status(struct mg_connection *, int status_code);
void mg_send_header(struct mg_connection *, const char *name, const char *value);
void mg_send_data(struct mg_connection *, const void *data, int data_len);
void mg_printf_data(struct mg_connection *, const char *format, ...);
加载问题已修复。但是 event_handler 被反复调用。它更像是没有关闭。当我尝试关闭浏览器窗口时,连接正在关闭并回调停止