C++ http服務

1.須要使用c++提供http服務,原本想使用libevent,可是通過一番搜索後,發現了只須要引用2個文件的mongoose庫。html

官方文檔:https://cesanta.com/docs/overview/intro.htmlc++

官方代碼:https://github.com/cesanta/mongoosegit

 

2.相關代碼github

#include "HttpService.h"

struct mg_serve_http_opts HttpService::s_http_server_opts; //請求事件處理
void HttpService::mgEvHandler(struct mg_connection *nc, int ev, void *p) { //處理request
    if (ev == MG_EV_HTTP_REQUEST) { struct http_message *msg = (struct http_message *)p; //body內容
        char* body = new char[msg->body.len + 1]; memset(body, 0, msg->body.len + 1); memcpy(body, msg->body.p, msg->body.len); //uri內容
        char* uri = new char[msg->uri.len + 1]; memset(uri, 0, msg->uri.len + 1); memcpy(uri, msg->uri.p, msg->uri.len); //返回body信息
        mgSendBody(nc, "body content"); //返回下載文件 //mgSendFile("相對於s_http_server_opts.document_root的文件路徑");

        delete uri; delete body; } } //發送body信息
void HttpService::mgSendBody(struct mg_connection *nc, const char *content) { mg_send_head(nc, 200, strlen(content), "Content-Type: text/plain\r\nConnection: close"); mg_send(nc, content, strlen(content)); nc->flags |= MG_F_SEND_AND_CLOSE; } //發送文件,文件的位置是相對於s_http_server_opts.document_root的路徑
void HttpService::mgSendFile(struct mg_connection *nc, struct http_message *hm, const char* filePath) { mg_http_serve_file(nc, hm, filePath, mg_mk_str("text/plain"), mg_mk_str("")); } //初始化並啓動
bool HttpService::start(const char *port) { struct mg_mgr mgr; struct mg_connection *nc; mg_mgr_init(&mgr, NULL); printf("Starting web server on port %s\n", port); nc = mg_bind(&mgr, port, mgEvHandler); if (nc == NULL) { printf("Failed to create listener\n"); return false; } // Set up HTTP server parameters
 mg_set_protocol_http_websocket(nc); s_http_server_opts.document_root = ".";  //文件相對路徑 Serve current directory
    s_http_server_opts.enable_directory_listing = "yes"; for (;;) { mg_mgr_poll(&mgr, 1000); //1s輪訓一次
 } mg_mgr_free(&mgr); return true; }

 

3.vs2019項目工程文件下載:vs2019_HttpSvr.zipweb

 

以上。websocket

相關文章
相關標籤/搜索