如何搭建一个http服务器

小灰灰 2023-06-23 13:23 126阅读 0赞

https://blog.csdn.net/u012234115/article/details/79596826
注意他的回复里面有详细的result=0的说明

http://www.websocket-test.com/
这是一个websocket在线测试工具

http 用postman测试特别好下载下来就可以了
在这里插入图片描述
库下载下来以后,直接用这两个就可以了,取消预编译头

  1. /* Get form variables */
  2. mg_get_http_var(&http_req->body, "n1", n1, sizeof(n1));
  3. mg_get_http_var(&http_req->body, "n2", n2, sizeof(n2));
  4. /*mg_get_http_var(&http_req->query_string, "n1", n1, sizeof(n1)); mg_get_http_var(&http_req->query_string, "n2", n2, sizeof(n2));*/

这些部分是通过地址或者body来传递参数的。

  1. http_server.h
  2. #pragma once
  3. #include <string>
  4. #include <string.h>
  5. #include <unordered_map>
  6. #include <unordered_set>
  7. #include <functional>
  8. #include "mongoose.h"
  9. // 定义http返回callback
  10. typedef void OnRspCallback(mg_connection *c, std::string);
  11. // 定义http请求handler
  12. using ReqHandler = std::function<bool(std::string, std::string, mg_connection *c, OnRspCallback)>;
  13. class HttpServer
  14. {
  15. public:
  16. HttpServer() { }
  17. ~HttpServer() { }
  18. void Init(const std::string &port); // 初始化设置
  19. bool Start(); // 启动httpserver
  20. bool Close(); // 关闭
  21. void AddHandler(const std::string &url, ReqHandler req_handler); // 注册事件处理函数
  22. void RemoveHandler(const std::string &url); // 移除时间处理函数
  23. static std::string s_web_dir; // 网页根目录
  24. static mg_serve_http_opts s_server_option; // web服务器选项
  25. static std::unordered_map<std::string, ReqHandler> s_handler_map; // 回调函数映射表
  26. private:
  27. // 静态事件响应函数
  28. static void OnHttpWebsocketEvent(mg_connection *connection, int event_type, void *event_data);
  29. static void HandleHttpEvent(mg_connection *connection, http_message *http_req);
  30. static void SendHttpRsp(mg_connection *connection, std::string rsp);
  31. static int isWebsocket(const mg_connection *connection); // 判断是否是websoket类型连接
  32. static void HandleWebsocketMessage(mg_connection *connection, int event_type, websocket_message *ws_msg);
  33. static void SendWebsocketMsg(mg_connection *connection, std::string msg); // 发送消息到指定连接
  34. static void BroadcastWebsocketMsg(std::string msg); // 给所有连接广播消息
  35. static std::unordered_set<mg_connection *> s_websocket_session_set; // 缓存websocket连接
  36. std::string m_port; // 端口
  37. mg_mgr m_mgr; // 连接管理器
  38. };

http_server.cpp

  1. #include "stdafx.h"
  2. #include "http_server.h"
  3. #include <utility>
  4. #include "http_server.h"
  5. #include <string>
  6. extern char g_Pic[1024 * 10];
  7. using namespace cv;
  8. using namespace std;
  9. #pragma warning(disable:4996)
  10. void readpic(char* InImgName, char*OutImgName)
  11. {
  12. //保存输入图像文件名和输出图像文件名
  13. /*char mInImgName[10]; char OutImgName[10];*/
  14. //图像数据长度
  15. int length;
  16. //文件指针
  17. FILE* fp;
  18. //以二进制方式打开图像
  19. if ((fp = fopen(InImgName, "rb")) == NULL)
  20. {
  21. //cout << "Open image failed!" << endl;
  22. exit(0);
  23. }
  24. //获取图像数据总长度
  25. fseek(fp, 0, SEEK_END);
  26. length = ftell(fp);
  27. rewind(fp);
  28. //根据图像数据长度分配内存buffer
  29. char* ImgBuffer = (char*)malloc(length * sizeof(char));
  30. //将图像数据读入buffer
  31. fread(ImgBuffer, length, 1, fp);
  32. memcpy(g_Pic, ImgBuffer, length);
  33. fclose(fp);
  34. //输入要保存的文件名
  35. //cout << "Enter the name you wanna to save:";
  36. //cin >> OutImgName;
  37. //以二进制写入方式
  38. if ((fp = fopen(OutImgName, "wb")) == NULL)
  39. {
  40. //cout << "Open File failed!" << endl;
  41. exit(0);
  42. }
  43. //从buffer中写数据到fp指向的文件中
  44. fwrite(ImgBuffer, length, 1, fp);
  45. //cout << "Done!" << endl;
  46. //关闭文件指针,释放buffer内存
  47. fclose(fp);
  48. free(ImgBuffer);
  49. }
  50. void HttpServer::Init(const std::string &port)
  51. {
  52. m_port = port;
  53. s_server_option.enable_directory_listing = "yes";
  54. s_server_option.document_root = s_web_dir.c_str();
  55. // 其他http设置
  56. // 开启 CORS,本项只针对主页加载有效
  57. // s_server_option.extra_headers = "Access-Control-Allow-Origin: *";
  58. }
  59. bool HttpServer::Start()
  60. {
  61. mg_mgr_init(&m_mgr, NULL);
  62. mg_connection *connection = mg_bind(&m_mgr, m_port.c_str(), HttpServer::OnHttpWebsocketEvent);
  63. if (connection == NULL)
  64. return false;
  65. // for both http and websocket
  66. mg_set_protocol_http_websocket(connection);
  67. printf("starting http server at port: %s\n", m_port.c_str());
  68. // loop
  69. while (true)
  70. mg_mgr_poll(&m_mgr, 500); // ms
  71. return true;
  72. }
  73. void HttpServer::OnHttpWebsocketEvent(mg_connection *connection, int event_type, void *event_data)
  74. {
  75. // 区分http和websocket
  76. if (event_type == MG_EV_HTTP_REQUEST)
  77. {
  78. http_message *http_req = (http_message *)event_data;
  79. HandleHttpEvent(connection, http_req);
  80. }
  81. else if (event_type == MG_EV_WEBSOCKET_HANDSHAKE_DONE ||
  82. event_type == MG_EV_WEBSOCKET_FRAME ||
  83. event_type == MG_EV_CLOSE)
  84. {
  85. websocket_message *ws_message = (struct websocket_message *)event_data;
  86. HandleWebsocketMessage(connection, event_type, ws_message);
  87. }
  88. }
  89. // ---- simple http ---- //
  90. static bool route_check(http_message *http_msg, char *route_prefix)
  91. {
  92. if (mg_vcmp(&http_msg->uri, route_prefix) == 0)
  93. return true;
  94. else
  95. return false;
  96. // TODO: 还可以判断 GET, POST, PUT, DELTE等方法
  97. //mg_vcmp(&http_msg->method, "GET");
  98. //mg_vcmp(&http_msg->method, "POST");
  99. //mg_vcmp(&http_msg->method, "PUT");
  100. //mg_vcmp(&http_msg->method, "DELETE");
  101. }
  102. void HttpServer::AddHandler(const string &url, ReqHandler req_handler)
  103. {
  104. if (s_handler_map.find(url) != s_handler_map.end())
  105. return;
  106. s_handler_map.insert(make_pair(url, req_handler));
  107. }
  108. void HttpServer::RemoveHandler(const std::string &url)
  109. {
  110. auto it = s_handler_map.find(url);
  111. if (it != s_handler_map.end())
  112. s_handler_map.erase(it);
  113. }
  114. void HttpServer::SendHttpRsp(mg_connection *connection, std::string rsp)
  115. {
  116. // --- 未开启CORS
  117. // 必须先发送header, 暂时还不能用HTTP/2.0
  118. mg_printf(connection, "%s", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n");
  119. // 以json形式返回
  120. //mg_printf_http_chunk(connection, "{ \"data\": %s }", rsp.c_str());
  121. mg_printf_http_chunk(connection, rsp.c_str());
  122. // 发送空白字符快,结束当前响应
  123. mg_send_http_chunk(connection, "", 0);
  124. // --- 开启CORS
  125. /*mg_printf(connection, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\n" "Cache-Control: no-cache\n" "Content-Length: %d\n" "Access-Control-Allow-Origin: *\n\n" "%s\n", rsp.length(), rsp.c_str()); */
  126. }
  127. void HttpServer::HandleHttpEvent(mg_connection *connection, http_message *http_req)
  128. {
  129. std::string req_str = std::string(http_req->message.p, http_req->message.len);
  130. //printf("got request: %s\n", req_str.c_str());
  131. // 先过滤是否已注册的函数回调
  132. /*std::string url = std::string(http_req->uri.p, http_req->uri.len); std::string query = std::string(http_req->query_string.p, http_req->query_string.len);*/
  133. //这里接收的是body内的数据
  134. std::string url = std::string(http_req->uri.p, http_req->uri.len);
  135. //std::string body = std::string(http_req->body.p, http_req->body.len);//收到的body
  136. //如果接收的是图片则用char* 来接收
  137. //---------------------------
  138. const int ImageLenth = http_req->body.len;
  139. char* ImageBody = (char*)malloc(sizeof(char)*ImageLenth);
  140. memset(ImageBody, 0, ImageLenth);
  141. memcpy(ImageBody, http_req->body.p, ImageLenth);
  142. //---------------------------
  143. string body = ImageBody;
  144. auto it = s_handler_map.find(url);
  145. if (it != s_handler_map.end())
  146. {
  147. ReqHandler handle_func = it->second;
  148. handle_func(url, body, connection, &HttpServer::SendHttpRsp);
  149. //handle_func(url, query, connection, &HttpServer::SendHttpRsp);
  150. }
  151. printf("recv body=%s\n\n", body.c_str());
  152. Json::Reader jsReader;
  153. Json::Value jsRes;
  154. jsRes.clear();
  155. /*if (!jsReader.parse(body.c_str(), body.c_str() + ImageLenth, jsRes)) return ; if (!jsRes.isObject()) return ;*/
  156. /*std::string raw_body; raw_body = jsRes["containerImg"].toStyledString(); cout<<"raw==================>>>>>>>>>>>>>>>>>>"<< raw_body<<endl;*/
  157. /*if (ImageLenth<100) { SendHttpRsp(connection, "HELLO WORLD"); delete ImageBody; printf("send success...\n\n"); return; }*/
  158. #ifdef NORMAL
  159. // 其他请求
  160. if (route_check(http_req, "/")) // index page
  161. mg_serve_http(connection, http_req, s_server_option);
  162. else if (route_check(http_req, "/api/hello"))
  163. {
  164. // 直接回传
  165. SendHttpRsp(connection, "welcome to httpserver");
  166. }
  167. else if (route_check(http_req, "/api/sum"))
  168. {
  169. // 简单post请求,加法运算测试
  170. char n1[100], n2[100];
  171. double result;
  172. /* Get form variables */
  173. mg_get_http_var(&http_req->body, "n1", n1, sizeof(n1));
  174. mg_get_http_var(&http_req->body, "n2", n2, sizeof(n2));
  175. /*mg_get_http_var(&http_req->query_string, "n1", n1, sizeof(n1)); mg_get_http_var(&http_req->query_string, "n2", n2, sizeof(n2));*/
  176. printf("n1=%s,n2=%s\n\n", n1, n2);
  177. /* Compute the result and send it back as a JSON object */
  178. result = strtod(n1, NULL) + strtod(n2, NULL);
  179. std::string resStr;
  180. //resStr = to_string(result);
  181. SendHttpRsp(connection, resStr);
  182. }
  183. else
  184. {
  185. mg_printf(
  186. connection,
  187. "%s",
  188. "HTTP/1.1 501 Not Implemented\r\n"
  189. "Content-Length: 0\r\n\r\n");
  190. }
  191. #else
  192. /* //模拟传递的图片 //----------------------------------------------------- //提前打开一个图片FILE* fp; //以二进制方式打开图像 FILE* fp; if ((fp = fopen("D:\\test\\2.jpg", "rb")) == NULL) { exit(0); } //获取图像数据总长度 fseek(fp, 0, SEEK_END); int length = ftell(fp); rewind(fp); //根据图像数据长度分配内存buffer char* ImgBuffer = (char*)malloc(length * sizeof(char)); //将图像数据读入buffer fread(ImgBuffer, length, 1, fp); fclose(fp); const int Max = length + 2; char tmp[1024*100] = { 0 }; memcpy(tmp, ImageBody, ImageLenth); printf("length=%d\nImage body=%4x\n\n", length, tmp); delete ImgBuffer; //----------------------------------------------------- */
  193. //std::string resStr;
  194. //std::string strJpgBaseContainer;
  195. //int len = 0;
  196. //
  197. //strJpgBaseContainer = base64_decode(raw_body);
  198. //len = strJpgBaseContainer.length();
  199. //cout << "strJpgBaseContainer==================>>>>>>>>>>>>>>>>>>" << strJpgBaseContainer << endl;
  200. show picture
  201. //const char * pImg= strJpgBaseContainer .c_str();
  202. //char dir[256]={0};
  203. //sprintf(dir, "D:\\test\\saff%x.jpg", GetTickCount());
  204. //FILE* pfile = fopen(dir, "wb");
  205. //if (pfile)
  206. //{
  207. // fwrite(raw_body.c_str(), len, 1, pfile);///fwrite(ImageBody, ImageLenth, 1, pfile);
  208. // fclose(pfile);
  209. // printf("write success...\n");
  210. //}
  211. 从文件中读入图像
  212. //Mat img = imread(dir, 1);
  213. 如果读入图像失败
  214. //if (img.empty())
  215. //{
  216. // fprintf(stderr, "Can not load image %s\n", dir);
  217. // //return ;
  218. //}
  219. 显示图像
  220. //imshow("image", img);
  221. 此函数等待按键,按键盘任意键就返回
  222. //waitKey();
  223. //resStr = ImageBody;
  224. //-----------------------------------------------------
  225. /* {\\"code\":\"11111111\",\"success\":false,\"message\":\"璋冩暣瑙掑害广东海关欢迎你 开箱成功\",\"data\":{\"crosswiseAngleChange\":\"15550\",\"lengthwiseAngleChange\":\"-1280\",\"eventId\":\"20191210151529_JS001_OOCU7892445\"}} {\"code\":\"00000000\",\"success\":true,\"message\":\"鎴愬姛开箱成功\",\"data\":{\"eventId\":\"20191210151529_JS001_OOCU7892445\",\"crosswiseAngle\":\"15700\",\"lengthwiseAngle\":\"-1280\"}} {\"code\":\"1\",\"success\":false,\"message\":\"鏈哄櫒浜鸿嚜鍔ㄥ寲璇嗗埆灏佸織鍙峰け璐?锛屾湭鎵惧埌灏佽瘑鍙峰浘鐗囥€?,\"data\":null} */
  226. string tmp;
  227. tmp = "{\"code\": \"11111111\",\"success\": false,\"message\": \"\u5e7f\u4e1c\u6d77\u5173\u6b22\u8fce\u4f60\u0020\u0020\u5f00\u7bb1\u5931\u8d25\",\"data\": {\"crosswiseAngleChange\": \"15550\",\"lengthwiseAngleChange\": \"-1280\",\"eventId\": \"20191210151529_JS001_OOCU7892445\"}}";
  228. //tmp = "{\"code\": \"00000000\",\"success\": true,\"message\": \"\u5f00\u7bb1\u6210\u529f\",\"data\": {\"eventId\": \"20191210151529_JS001_OOCU7892445\",\"crosswiseAngle\": \"15700\",\"lengthwiseAngle\": \"-1280\"}}";
  229. //tmp = "{\"code\": \"1\",\"success\": false,\"message\": \"\u4e2d\u534e\u4eba\u6c11\u5171\u548c\u56fd\u4e07\u5c81\",\"data\": \"\"}";
  230. Json::Value jsRes1;
  231. static int i = 0;
  232. if (0==i)
  233. {
  234. Sleep(5000);
  235. //jsRes1.clear();
  236. //jsRes1["data"]["eventId"] = "20191210151529_JS001_OOCU7892445";
  237. //jsRes1["data"]["crosswiseAngle"] = "15550";
  238. //jsRes1["data"]["lengthwiseAngle"] = "-1280";
  239. //jsRes1["code"] = "11111111";//
  240. //jsRes1["success"] = false;
  241. jsRes1["message"] = "\u5e7f\u4e1c\u6d77\u5173\u6b22\u8fce\u4f60\u0020\u0020\u5f00\u7bb1\u5931\u8d25";
  242. //jsRes1["message"] = "hello anzer,hello hello hello";
  243. jsRes1.clear();
  244. /*jsRes1["code"] = "11111111"; jsRes1["success"] = true; jsRes1["message"] = "hello anzer"; jsRes1["data"]["eventId"] = "20191210151529_JS001_OOCU7892445"; jsRes1["data"]["enlargerateChange"] = "4"; jsRes1["data"]["crosswiseAngle"] = "19222"; jsRes1["data"]["lengthwiseAngle"] = "-515"; jsRes1["data"]["pointX"] = "-515"; jsRes1["data"]["pointY"] = "-515";*/
  245. /*jsRes1["data"]["crosswiseAngle"] = "22025"; jsRes1["data"]["lengthwiseAngle"] = "-419";*/
  246. ++i;
  247. }
  248. else if(1==i)
  249. {
  250. //Sleep(5000);
  251. //jsRes1.clear();
  252. //jsRes1["data"]["eventId"] = "20191210151529_JS001_OOCU7892445";
  253. //jsRes1["data"]["crosswiseAngle"] = "15700";
  254. //jsRes1["data"]["lengthwiseAngle"] = "-1280";
  255. //jsRes1["data"] = "";
  256. //jsRes1["code"] = "00000000";
  257. //jsRes1["success"] = true;
  258. //jsRes1["message"] = "hello anzer,hello hello hello";
  259. jsRes1["message"] = "\u4e2d\u534e\u4eba\u6c11\u5171\u548c\u56fd\u4e07\u5c81";
  260. jsRes1.clear();
  261. jsRes1["code"] = "11111111";
  262. jsRes1["success"] = false;
  263. jsRes1["message"] = "hello anzer";
  264. jsRes1["data"]["eventId"] = "20191225093046_JS001_PONU7505962";
  265. /*jsRes1["data"]["crosswiseAngleChange"] = "21385"; jsRes1["data"]["lengthwiseAngleChange"] = "-198";*/
  266. jsRes1["data"]["crosswiseAngleChange"] = "19535";
  267. jsRes1["data"]["lengthwiseAngleChange"] = "-804";
  268. jsRes1["data"]["enlargerateChange"] = "16";
  269. jsRes1["data"]["pointX"] = "-515";
  270. jsRes1["data"]["pointY"] = "-515";
  271. ++i;
  272. }
  273. else if (2 == i)
  274. {
  275. //Sleep(5000);
  276. //jsRes1.clear();
  277. //jsRes1["data"]["eventId"] = "20191210151529_JS001_OOCU7892445";
  278. //jsRes1["data"]["crosswiseAngle"] = "15700";
  279. //jsRes1["data"]["lengthwiseAngle"] = "-1280";
  280. //jsRes1["data"] = "";
  281. //jsRes1["code"] = "00000000";
  282. //jsRes1["success"] = true;
  283. //jsRes1["message"] = "hello anzer,hello hello hello";
  284. jsRes1["message"] = "\u4e2d\u534e\u4eba\u6c11\u5171\u548c\u56fd\u4e07\u5c81";
  285. jsRes1.clear();
  286. jsRes1["code"] = "11111111";
  287. jsRes1["success"] = false;
  288. jsRes1["message"] = "hello anzer";
  289. jsRes1["data"]["eventId"] = "20191225093046_JS001_PONU7505962";
  290. /*jsRes1["data"]["crosswiseAngleChange"] = "21685"; jsRes1["data"]["lengthwiseAngleChange"] = "190";*/
  291. jsRes1["data"]["crosswiseAngleChange"] = "19665";
  292. jsRes1["data"]["lengthwiseAngleChange"] = "-870";
  293. jsRes1["data"]["enlargerateChange"] = "30";
  294. ++i;
  295. }
  296. else if(3==i)
  297. {
  298. //Sleep(5000);
  299. //jsRes1.clear();
  300. //jsRes1["data"]["eventId"] = "20191210151529_JS001_OOCU7892445";
  301. //jsRes1["data"]["crosswiseAngle"] = "-2280";
  302. //jsRes1["data"]["lengthwiseAngle"] = "1280";
  303. //jsRes1["code"] = "1";
  304. //jsRes1["success"] = false;
  305. jsRes1["message"] = "\u5e7f\u4e1c\u6d77\u5173\u6b22\u8fce\u4f60\u0020\u0020\u5f00\u7bb1\u5931\u8d25";
  306. //jsRes1["message"] = "hello anzer,hello hello hello";
  307. /*jsRes1.clear(); jsRes1["code"] = "1"; jsRes1["success"] = false; jsRes1["message"] = "hello anzer,hello hello hello";*/
  308. jsRes1.clear();
  309. jsRes1["code"] = "00000000";
  310. jsRes1["success"] = true;
  311. jsRes1["message"] = "hello anzer,open CSNU6393292";
  312. jsRes1["data"]["openArea"] = "";
  313. jsRes1["data"]["recogContainerNo"] = "CSNU6393292";
  314. jsRes1["data"]["recogSealNo"] = "12227063";
  315. jsRes1["data"]["containerNo"] = "CSNU6393292";
  316. jsRes1["data"]["sealNo"] = "12227063";
  317. jsRes1["data"]["canOpen"] = false;
  318. jsRes1["data"]["comparisonInfo"] = "结束定点拍照任务";
  319. jsRes1["data"]["eventId"] = "20191225093320_JS002_CSNU6393292";
  320. i++;
  321. }
  322. else
  323. {
  324. jsRes1.clear();
  325. i = 0;
  326. }
  327. //--------------------------------------------------------
  328. tmp = jsRes1.toStyledString();
  329. SendHttpRsp(connection, tmp);
  330. printf("send body=%s\n\n", tmp.c_str());
  331. printf("------------------------------------------------------------------------------\n\n");
  332. //-----------------------------------------------------
  333. //SendHttpRsp(connection, resStr);
  334. delete ImageBody;
  335. #endif // 0
  336. }
  337. // ---- websocket ---- //
  338. int HttpServer::isWebsocket(const mg_connection *connection)
  339. {
  340. return connection->flags & MG_F_IS_WEBSOCKET;
  341. }
  342. void HttpServer::HandleWebsocketMessage(mg_connection *connection, int event_type, websocket_message *ws_msg)
  343. {
  344. if (event_type == MG_EV_WEBSOCKET_HANDSHAKE_DONE)
  345. {
  346. printf("client websocket connected\n");
  347. // 获取连接客户端的IP和端口
  348. char addr[32];
  349. mg_sock_addr_to_str(&connection->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
  350. printf("client addr: %s\n", addr);
  351. // 添加 session
  352. s_websocket_session_set.insert(connection);
  353. SendWebsocketMsg(connection, "client websocket connected");
  354. }
  355. else if (event_type == MG_EV_WEBSOCKET_FRAME)
  356. {
  357. mg_str received_msg = {
  358. (char *)ws_msg->data, ws_msg->size
  359. };
  360. char buff[1024] = { 0 };
  361. strncpy(buff, received_msg.p, received_msg.len); // must use strncpy, specifiy memory pointer and length
  362. // do sth to process request
  363. printf("received msg: %s\n", buff);
  364. SendWebsocketMsg(connection, "send your msg back: " + std::string(buff));
  365. //BroadcastWebsocketMsg("broadcast msg: " + std::string(buff));
  366. }
  367. else if (event_type == MG_EV_CLOSE)
  368. {
  369. if (isWebsocket(connection))
  370. {
  371. printf("client websocket closed\n");
  372. // 移除session
  373. if (s_websocket_session_set.find(connection) != s_websocket_session_set.end())
  374. s_websocket_session_set.erase(connection);
  375. }
  376. }
  377. }
  378. void HttpServer::SendWebsocketMsg(mg_connection *connection, std::string msg)
  379. {
  380. mg_send_websocket_frame(connection, WEBSOCKET_OP_TEXT, msg.c_str(), strlen(msg.c_str()));
  381. }
  382. void HttpServer::BroadcastWebsocketMsg(std::string msg)
  383. {
  384. for (mg_connection *connection : s_websocket_session_set)
  385. mg_send_websocket_frame(connection, WEBSOCKET_OP_TEXT, msg.c_str(), strlen(msg.c_str()));
  386. }
  387. bool HttpServer::Close()
  388. {
  389. mg_mgr_free(&m_mgr);
  390. return true;
  391. }

主函数

  1. // httpserver.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include <memory>
  6. #include "http_server.h"
  7. #pragma warning(disable:4996)
  8. using namespace std;
  9. // 初始化HttpServer静态类成员
  10. mg_serve_http_opts HttpServer::s_server_option;
  11. std::string HttpServer::s_web_dir = "./web";
  12. std::unordered_map<std::string, ReqHandler> HttpServer::s_handler_map;
  13. std::unordered_set<mg_connection *> HttpServer::s_websocket_session_set;
  14. char g_Pic[1024 * 10] = { 0 };
  15. bool handle_fun1(std::string url, std::string body, mg_connection *c, OnRspCallback rsp_callback)
  16. {
  17. // do sth
  18. std::cout << "handle fun1" << std::endl;
  19. std::cout << "url: " << url << std::endl;
  20. std::cout << "body: " << body << std::endl;
  21. rsp_callback(c, "rsp1");
  22. return true;
  23. }
  24. bool handle_fun2(std::string url, std::string body, mg_connection *c, OnRspCallback rsp_callback)
  25. {
  26. // do sth
  27. std::cout << "handle fun2" << std::endl;
  28. std::cout << "url: " << url << std::endl;
  29. std::cout << "body: " << body << std::endl;
  30. rsp_callback(c, "rsp2");
  31. return true;
  32. }
  33. int main(int argc, char *argv[])
  34. {
  35. std::string port = "18899";
  36. auto http_server = std::shared_ptr<HttpServer>(new HttpServer);
  37. http_server->Init(port);
  38. // add handler
  39. http_server->AddHandler("/api/fun1", handle_fun1);
  40. http_server->AddHandler("/api/fun2", handle_fun2);
  41. http_server->Start();
  42. return 0;
  43. }

mongoose.h

mongoose.cpp

  1. 在这里插入代码片

发表评论

表情:
评论列表 (有 0 条评论,126人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Http服务器

    一、Nginx介绍 > Nginx是一个高性能的HTTP和方向代理服务,也是一个IMAP/POP3/SMTP服务。 > > 其特点是占用内存少,并发能力强,中国大陆使用

    相关 如何服务器

    本文将介绍如何搭建服务器: 作为一个大学生,且作为一个编程者,拥有一个自己的服务器会对我们的学习带来极大的方便。而且很多服务器公司都对我们大学生有很大的优惠,毕业了就无法