gpt4 book ai didi

c++ - mongoose web 服务器 helloworld 程序

转载 作者:IT老高 更新时间:2023-10-28 21:56:14 29 4
gpt4 key购买 nike

我遇到了一个名为 mongoose 的嵌入式 Web 服务器和 http://code.google.com/p/mongoose/我阅读了 wiki,它很棒,我搜索了一些示例 hello world 程序,但我找不到它......我找到了一些示例,但它是用 c++ 为 windows 编写的,任何人都可以提供一个示例 c 程序来运行这个网络服务器..

最佳答案

很简单,首先你需要实现回调函数:

void *event_handler(enum mg_event event,
struct mg_connection *conn) {

const struct mg_request_info *request_info = mg_get_request_info(conn);

static void* done = "done";

if (event == MG_NEW_REQUEST) {
if (strcmp(request_info->uri, "/hello") == 0) {
// handle c[renderer] request
if(strcmp(request_info->request_method, "GET") != 0) {
// send error (we only care about HTTP GET)
mg_printf(conn, "HTTP/1.1 %d Error (%s)\r\n\r\n%s",
500,
"we only care about HTTP GET",
"we only care about HTTP GET");
// return not null means we handled the request
return done;
}

// handle your GET request to /hello
char* content = "Hello World!";
char* mimeType = "text/plain";
int contentLength = strlen(content);

mg_printf(conn,
"HTTP/1.1 200 OK\r\n"
"Cache: no-cache\r\n"
"Content-Type: %s\r\n"
"Content-Length: %d\r\n"
"\r\n",
mimeType,
contentLength);
mg_write(conn, content, contentLength);
return done;
}
}
// in this example i only handle /hello
mg_printf(conn, "HTTP/1.1 %d Error (%s)\r\n\r\n%s",
500, /* This the error code you want to send back*/
"Invalid Request.",
"Invalid Request.");
return done;
}

// No suitable handler found, mark as not processed. Mongoose will
// try to serve the request.
return NULL;
}

然后你需要启动服务器:

int main(int argc, char **argv) {

/* Default options for the HTTP server */
const char *options[] = {
"listening_ports", "8081",
"num_threads", "10",
NULL
};

/* Initialize HTTP layer */
static struct mg_context *ctx;

ctx = mg_start(&event_handler, options);
if(ctx == NULL) {
exit(EXIT_FAILURE);
}

puts("Server running, press enter to exit\n");
getchar();
mg_stop(ctx);

return EXIT_SUCCESS;
}

关于c++ - mongoose web 服务器 helloworld 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5093330/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com