Mongoose源码分析之--简单的服务器搭建(C语言)

来源:互联网 发布:ibm oa软件 编辑:程序博客网 时间:2024/05/19 02:21
测试半天一直不行,发现原版少写个return null, 什么都不需要处理 可以实现web
由于在IOS终端设备上播放实时的TS流,要使用MPMoviePlayerController控件,必须采用Http请求的形式去请求数据,而TS流的来源是通过HTTP请求拿到的,需要再把这个拿到的TS流发送给IOS播放器,所以试图自己搭建一个HTTP服务器,为此学习了Mongoose的源码,这是一个非常轻便,易用,且性能稳定的一套Web服务器源码,总代码不到五千行,在我看来是学习HTTP服务器搭建的一个好的例子。根据我对Mongoose源码的查看和分析,建立一个http服务器的流程是:    开启一个master线程:监听线程->监听所有的套接字读状态是否发生变化(判断是否有套接字请求连接),将请求连接的套接字加入到全局的queue[20]中去。如果队列已满,则等待。    同时开启N个worker线程:不断从queue中拿出头套接字进行连接处理,如果队列为空,则等待。最简单的一个HTTP服务器搭建C语言代码如下。
</pre><pre code_snippet_id="1838284" snippet_file_name="blog_20160818_1_4425331" class="prettyprint" name="code" style="white-space: nowrap; word-wrap: break-word; box-sizing: border-box; position: relative; overflow-y: hidden; overflow-x: auto; margin-top: 0px; margin-bottom: 1.1em; font-family: 'Source Code Pro', monospace; padding: 5px 5px 5px 60px; font-size: 14px; line-height: 1.45; word-break: break-all; color: rgb(51, 51, 51); border: 1px solid rgba(128, 128, 128, 0.0745098); border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; background-color: rgba(128, 128, 128, 0.0470588);">
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

以上为

#include <stdio.h>#include <string.h>#include "mongoose.h"static void *callback(enum mg_event event,                      struct mg_connection *conn) {printf("cb %s\n", mg_get_request_info(conn)->log_message);  if (event == MG_NEW_REQUEST) {       //response for http request.   }        return NULL;}int main(void) {  struct mg_context *ctx; // const char *options[] = {"listening_ports", "8080", NULL};  ctx = mg_start(&callback, NULL, /*options*/NULL);        printf(" started on port(s) %s with web root [%s]\n",               "a", mg_get_option(ctx, "listening_ports"));getchar();  // Wait until user hits "enter"printf("char \n");  mg_stop(ctx);printf("bye\n");  return 0;}


搭建一个简单的本地服务器,端口为8080,运行起来之后在本机的浏览器中访问http://127.0.0.1:8080/地址则可以访问到本机的根目录。如果需要自定义服务器对请求的响应,那么可以在代码中回调函数callback中自行实现。
0 0
原创粉丝点击