首先,本人刚刚开始开源代码精读,写的不对的地方,大家轻拍,一起进步。本文是对Tinyhttpd的一次精读,大家每天都在用着http服务,很多人也一直活跃在上层,使用IIS、Apache等,大家是否想看看http服务器大概是怎么运作的,通过一个500多行的源码加上完整的注释,和大家逛一逛http服务器。Tinyhttpd真的非常适合阅读尤其是刚入门的,清晰的代码,简单的makefile...其实有很多分析tinyghttpd的,这边抱着人家写的是人家,自己写的才是自己的态度,写的尽量详细,尽量简单,很多都写在代码注释里面,也把学习中的一些坑翻出来和大家一起读读,吸取将近20年前的大神通过500行代码带给我们的财富。不管你是写c的,或者C#,js亦或java,只要用到http的都欢迎读读。
大家看后如果觉得我有写的不对的地方,欢迎指出~~

附上注解代码的github地址:https://github.com/nengm/Tinyhttpd

1.首先是一张图 全解了Tinyhttp是如何运作的,我觉得图说明比我用文字描述的要清晰,语言功底不太给力。

2. 主要函数简略说明,代码中进行了详细注释。

main          主函数
startup         绑定监听套接字
accept_request     每次收到请求,创建一个线程来处理接受到的请求
serve_file      接读取文件返回给请求的http客户端
execute_cgi     执行cgi文件

3.注意点

注意点1:

index.html必须没有执行权限,否则看不到内容,并且会产生Program received signal SIGPIPE, Broken pipe,因为程序中如果有可执行权限会当cgi脚本处理。所以假如html有执行权限先把它去除了,chmod 600 index.html

color.cgi、date.cgi必须要有执行权限。

注意点2:

color.cgi是用perl写的,相信大家很少接触了。所以可以引用网上一个简单的例子,换成一个shell写的cgi测试

#!/bin/bash
echo "Content-Type: text/html"
echo
echo "<HTML><BODY>"
echo "<CENTER>Today is:</CENTER>"
echo "<CENTER><B>"
date
echo "</B></CENTER>"
echo "</BODY></HTML>"

4.操作

1.执行make,生成成功,./httpd启动成功。

2.如果在当前linux下的firefox下执行。直接在浏览器中输入

3.在windows中测试,

4.测试执行自带的perl写的cgi脚本

5.进入index2.html页面,测试shell写的cgi脚本。

5.代码

  1. /* J. David's webserver */
  2. /* This is a simple webserver.
  3. * Created November 1999 by J. David Blackstone.
  4. * CSE 4344 (Network concepts), Prof. Zeigler
  5. * University of Texas at Arlington
  6. */
  7. /* This program compiles for Sparc Solaris 2.6.
  8. * To compile for Linux:
  9. * 1) Comment out the #include <pthread.h> line.
  10. * 2) Comment out the line that defines the variable newthread.
  11. * 3) Comment out the two lines that run pthread_create().
  12. * 4) Uncomment the line that runs accept_request().
  13. * 5) Remove -lsocket from the Makefile.
  14. */
  15. #include <stdio.h>
  16. #include <sys/socket.h>
  17. #include <sys/types.h>
  18. #include <netinet/in.h>
  19. #include <arpa/inet.h>
  20. #include <unistd.h>
  21. #include <ctype.h>
  22. #include <strings.h>
  23. #include <string.h>
  24. #include <sys/stat.h>
  25. #include <pthread.h>
  26. #include <sys/wait.h>
  27. #include <stdlib.h>
  28.  
  29. //宏定义,是否是空格
  30. #define ISspace(x) isspace((int)(x))
  31.  
  32. #define SERVER_STRING "Server: jdbhttpd/0.1.0\r\n"
  33.  
  34. //每次收到请求,创建一个线程来处理接受到的请求
  35. //把client_sock转成地址作为参数传入pthread_create
  36. void accept_request(void *arg);
  37.  
  38. //错误请求
  39. void bad_request(int);
  40.  
  41. //读取文件
  42. void cat(int, FILE *);
  43.  
  44. //无法执行
  45. void cannot_execute(int);
  46.  
  47. //错误输出
  48. void error_die(const char *);
  49.  
  50. //执行cig脚本
  51. void execute_cgi(int, const char *, const char *, const char *);
  52.  
  53. //得到一行数据,只要发现c为\n,就认为是一行结束,如果读到\r,再用MSG_PEEK的方式读入一个字符,如果是\n,从socket用读出
  54. //如果是下个字符则不处理,将c置为\n,结束。如果读到的数据为0中断,或者小于0,也视为结束,c置为\n
  55. int get_line(int, char *, int);
  56.  
  57. //返回http头
  58. void headers(int, const char *);
  59.  
  60. //没有发现文件
  61. void not_found(int);
  62.  
  63. //如果不是CGI文件,直接读取文件返回给请求的http客户端
  64. void serve_file(int, const char *);
  65.  
  66. //开启tcp连接,绑定端口等操作
  67. int startup(u_short *);
  68.  
  69. //如果不是Get或者Post,就报方法没有实现
  70. void unimplemented(int);
  71.  
  72. // Http请求,后续主要是处理这个头
  73. //
  74. // GET / HTTP/1.1
  75. // Host: 192.168.0.23:47310
  76. // Connection: keep-alive
  77. // Upgrade-Insecure-Requests: 1
  78. // User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
  79. // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*; q = 0.8
  80. // Accept - Encoding: gzip, deflate, sdch
  81. // Accept - Language : zh - CN, zh; q = 0.8
  82. // Cookie: __guid = 179317988.1576506943281708800.1510107225903.8862; monitor_count = 5
  83. //
  84.  
  85. // POST / color1.cgi HTTP / 1.1
  86. // Host: 192.168.0.23 : 47310
  87. // Connection : keep - alive
  88. // Content - Length : 10
  89. // Cache - Control : max - age = 0
  90. // Origin : http ://192.168.0.23:40786
  91. // Upgrade - Insecure - Requests : 1
  92. // User - Agent : Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 55.0.2883.87 Safari / 537.36
  93. // Content - Type : application / x - www - form - urlencoded
  94. // Accept : text / html, application / xhtml + xml, application / xml; q = 0.9, image / webp, */*;q=0.8
  95. // Referer: http://192.168.0.23:47310/
  96. // Accept-Encoding: gzip, deflate
  97. // Accept-Language: zh-CN,zh;q=0.8
  98. // Cookie: __guid=179317988.1576506943281708800.1510107225903.8862; monitor_count=281
  99. // Form Data
  100. // color=gray
  101.  
  102. /**********************************************************************/
  103. /* A request has caused a call to accept() on the server port to
  104. * return. Process the request appropriately.
  105. * Parameters: the socket connected to the client */
  106. /**********************************************************************/
  107. void accept_request(void *arg)
  108. {
  109. //socket
  110. int client = (intptr_t)arg;
  111. char buf[];
  112. int numchars;
  113. char method[];
  114. char url[];
  115. char path[];
  116. size_t i, j;
  117. struct stat st;
  118. int cgi = ; /* becomes true if server decides this is a CGI
  119. * program */
  120. char *query_string = NULL;
  121. //根据上面的Get请求,可以看到这边就是取第一行
  122. //这边都是在处理第一条http信息
  123. //"GET / HTTP/1.1\n"
  124. numchars = get_line(client, buf, sizeof(buf));
  125. i = ; j = ;
  126.  
  127. //第一行字符串提取Get
  128. while (!ISspace(buf[j]) && (i < sizeof(method) - ))
  129. {
  130. method[i] = buf[j];
  131. i++; j++;
  132. }
  133. //结束
  134. method[i] = '\0';
  135.  
  136. //判断是Get还是Post
  137. if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
  138. {
  139. unimplemented(client);
  140. return;
  141. }
  142.  
  143. //如果是POST,cgi置为1
  144. if (strcasecmp(method, "POST") == )
  145. cgi = ;
  146.  
  147. i = ;
  148. //跳过空格
  149. while (ISspace(buf[j]) && (j < sizeof(buf)))
  150. j++;
  151.  
  152. //得到 "/" 注意:如果你的http的网址为http://192.168.0.23:47310/index.html
  153. // 那么你得到的第一条http信息为GET /index.html HTTP/1.1,那么
  154. // 解析得到的就是/index.html
  155. while (!ISspace(buf[j]) && (i < sizeof(url) - ) && (j < sizeof(buf)))
  156. {
  157. url[i] = buf[j];
  158. i++; j++;
  159. }
  160. url[i] = '\0';
  161.  
  162. //判断Get请求
  163. if (strcasecmp(method, "GET") == )
  164. {
  165. query_string = url;
  166. while ((*query_string != '?') && (*query_string != '\0'))
  167. query_string++;
  168. if (*query_string == '?')
  169. {
  170. cgi = ;
  171. *query_string = '\0';
  172. query_string++;
  173. }
  174. }
  175.  
  176. //路径
  177. sprintf(path, "htdocs%s", url);
  178.  
  179. //默认地址,解析到的路径如果为/,则自动加上index.html
  180. if (path[strlen(path) - ] == '/')
  181. strcat(path, "index.html");
  182.  
  183. //获得文件信息
  184. if (stat(path, &st) == -) {
  185. //把所有http信息读出然后丢弃
  186. while ((numchars > ) && strcmp("\n", buf)) /* read & discard headers */
  187. numchars = get_line(client, buf, sizeof(buf));
  188.  
  189. //没有找到
  190. not_found(client);
  191. }
  192. else
  193. {
  194. if ((st.st_mode & S_IFMT) == S_IFDIR)
  195. strcat(path, "/index.html");
  196. //如果你的文件默认是有执行权限的,自动解析成cgi程序,如果有执行权限但是不能执行,会接受到报错信号
  197. if ((st.st_mode & S_IXUSR) ||
  198. (st.st_mode & S_IXGRP) ||
  199. (st.st_mode & S_IXOTH) )
  200. cgi = ;
  201. if (!cgi)
  202. //接读取文件返回给请求的http客户端
  203. serve_file(client, path);
  204. else
  205. //执行cgi文件
  206. execute_cgi(client, path, method, query_string);
  207. }
  208. //执行完毕关闭socket
  209. close(client);
  210. }
  211.  
  212. /**********************************************************************/
  213. /* Inform the client that a request it has made has a problem.
  214. * Parameters: client socket */
  215. /**********************************************************************/
  216. void bad_request(int client)
  217. {
  218. char buf[];
  219.  
  220. sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n");
  221. send(client, buf, sizeof(buf), );
  222. sprintf(buf, "Content-type: text/html\r\n");
  223. send(client, buf, sizeof(buf), );
  224. sprintf(buf, "\r\n");
  225. send(client, buf, sizeof(buf), );
  226. sprintf(buf, "<P>Your browser sent a bad request, ");
  227. send(client, buf, sizeof(buf), );
  228. sprintf(buf, "such as a POST without a Content-Length.\r\n");
  229. send(client, buf, sizeof(buf), );
  230. }
  231.  
  232. /**********************************************************************/
  233. /* Put the entire contents of a file out on a socket. This function
  234. * is named after the UNIX "cat" command, because it might have been
  235. * easier just to do something like pipe, fork, and exec("cat").
  236. * Parameters: the client socket descriptor
  237. * FILE pointer for the file to cat */
  238. /**********************************************************************/
  239.  
  240. //得到文件内容,发送
  241. void cat(int client, FILE *resource)
  242. {
  243. char buf[];
  244.  
  245. fgets(buf, sizeof(buf), resource);
  246. //循环读
  247. while (!feof(resource))
  248. {
  249. send(client, buf, strlen(buf), );
  250. fgets(buf, sizeof(buf), resource);
  251. }
  252. }
  253.  
  254. /**********************************************************************/
  255. /* Inform the client that a CGI script could not be executed.
  256. * Parameter: the client socket descriptor. */
  257. /**********************************************************************/
  258. void cannot_execute(int client)
  259. {
  260. char buf[];
  261.  
  262. sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n");
  263. send(client, buf, strlen(buf), );
  264. sprintf(buf, "Content-type: text/html\r\n");
  265. send(client, buf, strlen(buf), );
  266. sprintf(buf, "\r\n");
  267. send(client, buf, strlen(buf), );
  268. sprintf(buf, "<P>Error prohibited CGI execution.\r\n");
  269. send(client, buf, strlen(buf), );
  270. }
  271.  
  272. /**********************************************************************/
  273. /* Print out an error message with perror() (for system errors; based
  274. * on value of errno, which indicates system call errors) and exit the
  275. * program indicating an error. */
  276. /**********************************************************************/
  277. void error_die(const char *sc)
  278. {
  279. perror(sc);
  280. exit();
  281. }
  282.  
  283. /**********************************************************************/
  284. /* Execute a CGI script. Will need to set environment variables as
  285. * appropriate.
  286. * Parameters: client socket descriptor
  287. * path to the CGI script */
  288. /**********************************************************************/
  289. void execute_cgi(int client, const char *path,
  290. const char *method, const char *query_string)
  291. {
  292. //缓冲区
  293. char buf[];
  294.  
  295. //2根管道
  296. int cgi_output[];
  297. int cgi_input[];
  298.  
  299. //进程pid和状态
  300. pid_t pid;
  301. int status;
  302.  
  303. int i;
  304. char c;
  305.  
  306. //读取的字符数
  307. int numchars = ;
  308.  
  309. //http的content_length
  310. int content_length = -;
  311.  
  312. //默认字符
  313. buf[] = 'A'; buf[] = '\0';
  314.  
  315. //忽略大小写比较字符串
  316. if (strcasecmp(method, "GET") == )
  317. //读取数据,把整个header都读掉,以为Get写死了直接读取index.html,没有必要分析余下的http信息了
  318. while ((numchars > ) && strcmp("\n", buf)) /* read & discard headers */
  319. numchars = get_line(client, buf, sizeof(buf));
  320. else /* POST */
  321. {
  322. numchars = get_line(client, buf, sizeof(buf));
  323. while ((numchars > ) && strcmp("\n", buf))
  324. {
  325. //如果是POST请求,就需要得到Content-Length,Content-Length:这个字符串一共长为15位,所以
  326. //取出头部一句后,将第16位设置结束符,进行比较
  327. //第16位置为结束
  328. buf[] = '\0';
  329. if (strcasecmp(buf, "Content-Length:") == )
  330. //内存从第17位开始就是长度,将17位开始的所有字符串转成整数就是content_length
  331. content_length = atoi(&(buf[]));
  332. numchars = get_line(client, buf, sizeof(buf));
  333. }
  334. if (content_length == -) {
  335. bad_request(client);
  336. return;
  337. }
  338. }
  339.  
  340. sprintf(buf, "HTTP/1.0 200 OK\r\n");
  341. send(client, buf, strlen(buf), );
  342. //建立output管道
  343. if (pipe(cgi_output) < ) {
  344. cannot_execute(client);
  345. return;
  346. }
  347.  
  348. //建立input管道
  349. if (pipe(cgi_input) < ) {
  350. cannot_execute(client);
  351. return;
  352. }
  353. // fork后管道都复制了一份,都是一样的
  354. // 子进程关闭2个无用的端口,避免浪费
  355. // ×<------------------------->1 output
  356. // 0<-------------------------->× input
  357.  
  358. // 父进程关闭2个无用的端口,避免浪费
  359. // 0<-------------------------->× output
  360. // ×<------------------------->1 input
  361. // 此时父子进程已经可以通信
  362.  
  363. //fork进程,子进程用于执行CGI
  364. //父进程用于收数据以及发送子进程处理的回复数据
  365. if ( (pid = fork()) < ) {
  366. cannot_execute(client);
  367. return;
  368. }
  369. if (pid == ) /* child: CGI script */
  370. {
  371. char meth_env[];
  372. char query_env[];
  373. char length_env[];
  374.  
  375. //子进程输出重定向到output管道的1端
  376. dup2(cgi_output[], );
  377. //子进程输入重定向到input管道的0端
  378. dup2(cgi_input[], );
  379.  
  380. //关闭无用管道口
  381. close(cgi_output[]);
  382. close(cgi_input[]);
  383.  
  384. //CGI环境变量
  385. sprintf(meth_env, "REQUEST_METHOD=%s", method);
  386. putenv(meth_env);
  387. if (strcasecmp(method, "GET") == ) {
  388. sprintf(query_env, "QUERY_STRING=%s", query_string);
  389. putenv(query_env);
  390. }
  391. else { /* POST */
  392. sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
  393. putenv(length_env);
  394. }
  395. //替换执行path
  396. execl(path, path, NULL);
  397. //int m = execl(path, path, NULL);
  398. //如果path有问题,例如将html网页改成可执行的,但是执行后m为-1
  399. //退出子进程,管道被破坏,但是父进程还在往里面写东西,触发Program received signal SIGPIPE, Broken pipe.
  400. exit();
  401. } else { /* parent */
  402.  
  403. //关闭无用管道口
  404. close(cgi_output[]);
  405. close(cgi_input[]);
  406. if (strcasecmp(method, "POST") == )
  407. for (i = ; i < content_length; i++) {
  408. //得到post请求数据,写到input管道中,供子进程使用
  409. recv(client, &c, , );
  410. write(cgi_input[], &c, );
  411. }
  412. //从output管道读到子进程处理后的信息,然后send出去
  413. while (read(cgi_output[], &c, ) > )
  414. send(client, &c, , );
  415.  
  416. //完成操作后关闭管道
  417. close(cgi_output[]);
  418. close(cgi_input[]);
  419.  
  420. //等待子进程返回
  421. waitpid(pid, &status, );
  422.  
  423. }
  424. }
  425.  
  426. /**********************************************************************/
  427. /* Get a line from a socket, whether the line ends in a newline,
  428. * carriage return, or a CRLF combination. Terminates the string read
  429. * with a null character. If no newline indicator is found before the
  430. * end of the buffer, the string is terminated with a null. If any of
  431. * the above three line terminators is read, the last character of the
  432. * string will be a linefeed and the string will be terminated with a
  433. * null character.
  434. * Parameters: the socket descriptor
  435. * the buffer to save the data in
  436. * the size of the buffer
  437. * Returns: the number of bytes stored (excluding null) */
  438. /**********************************************************************/
  439.  
  440. //得到一行数据,只要发现c为\n,就认为是一行结束,如果读到\r,再用MSG_PEEK的方式读入一个字符,如果是\n,从socket用读出
  441. //如果是下个字符则不处理,将c置为\n,结束。如果读到的数据为0中断,或者小于0,也视为结束,c置为\n
  442. int get_line(int sock, char *buf, int size)
  443. {
  444. int i = ;
  445. char c = '\0';
  446. int n;
  447.  
  448. while ((i < size - ) && (c != '\n'))
  449. {
  450. n = recv(sock, &c, , );
  451. /* DEBUG printf("%02X\n", c); */
  452. if (n > )
  453. {
  454. if (c == '\r')
  455. {
  456. //偷窥一个字节,如果是\n就读走
  457. n = recv(sock, &c, , MSG_PEEK);
  458. /* DEBUG printf("%02X\n", c); */
  459. if ((n > ) && (c == '\n'))
  460. recv(sock, &c, , );
  461. else
  462. //不是\n(读到下一行的字符)或者没读到,置c为\n 跳出循环,完成一行读取
  463. c = '\n';
  464. }
  465. buf[i] = c;
  466. i++;
  467. }
  468. else
  469. c = '\n';
  470. }
  471. buf[i] = '\0';
  472.  
  473. return(i);
  474. }
  475.  
  476. /**********************************************************************/
  477. /* Return the informational HTTP headers about a file. */
  478. /* Parameters: the socket to print the headers on
  479. * the name of the file */
  480. /**********************************************************************/
  481.  
  482. //加入http的headers
  483. void headers(int client, const char *filename)
  484. {
  485. char buf[];
  486. (void)filename; /* could use filename to determine file type */
  487.  
  488. strcpy(buf, "HTTP/1.0 200 OK\r\n");
  489. send(client, buf, strlen(buf), );
  490. strcpy(buf, SERVER_STRING);
  491. send(client, buf, strlen(buf), );
  492. sprintf(buf, "Content-Type: text/html\r\n");
  493. send(client, buf, strlen(buf), );
  494. strcpy(buf, "\r\n");
  495. send(client, buf, strlen(buf), );
  496. }
  497.  
  498. /**********************************************************************/
  499. /* Give a client a 404 not found status message. */
  500. /**********************************************************************/
  501.  
  502. //如果资源没有找到得返回给客户端下面的信息
  503. void not_found(int client)
  504. {
  505. char buf[];
  506.  
  507. sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
  508. send(client, buf, strlen(buf), );
  509. sprintf(buf, SERVER_STRING);
  510. send(client, buf, strlen(buf), );
  511. sprintf(buf, "Content-Type: text/html\r\n");
  512. send(client, buf, strlen(buf), );
  513. sprintf(buf, "\r\n");
  514. send(client, buf, strlen(buf), );
  515. sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n");
  516. send(client, buf, strlen(buf), );
  517. sprintf(buf, "<BODY><P>The server could not fulfill\r\n");
  518. send(client, buf, strlen(buf), );
  519. sprintf(buf, "your request because the resource specified\r\n");
  520. send(client, buf, strlen(buf), );
  521. sprintf(buf, "is unavailable or nonexistent.\r\n");
  522. send(client, buf, strlen(buf), );
  523. sprintf(buf, "</BODY></HTML>\r\n");
  524. send(client, buf, strlen(buf), );
  525. }
  526.  
  527. /**********************************************************************/
  528. /* Send a regular file to the client. Use headers, and report
  529. * errors to client if they occur.
  530. * Parameters: a pointer to a file structure produced from the socket
  531. * file descriptor
  532. * the name of the file to serve */
  533. /**********************************************************************/
  534.  
  535. //如果不是CGI文件,直接读取文件返回给请求的http客户端
  536. void serve_file(int client, const char *filename)
  537. {
  538. FILE *resource = NULL;
  539. int numchars = ;
  540. char buf[];
  541.  
  542. //默认字符
  543. buf[] = 'A'; buf[] = '\0';
  544. while ((numchars > ) && strcmp("\n", buf)) /* read & discard headers */
  545. numchars = get_line(client, buf, sizeof(buf));
  546.  
  547. resource = fopen(filename, "r");
  548. if (resource == NULL)
  549. not_found(client);
  550. else
  551. {
  552. headers(client, filename);
  553. cat(client, resource);
  554. }
  555. fclose(resource);
  556. }
  557.  
  558. /**********************************************************************/
  559. /* This function starts the process of listening for web connections
  560. * on a specified port. If the port is 0, then dynamically allocate a
  561. * port and modify the original port variable to reflect the actual
  562. * port.
  563. * Parameters: pointer to variable containing the port to connect on
  564. * Returns: the socket */
  565. /**********************************************************************/
  566. int startup(u_short *port)
  567. {
  568. int httpd = ;
  569. struct sockaddr_in name;
  570.  
  571. httpd = socket(PF_INET, SOCK_STREAM, );
  572. if (httpd == -)
  573. error_die("socket");
  574. memset(&name, , sizeof(name));
  575. name.sin_family = AF_INET;
  576. name.sin_port = htons(*port);
  577. name.sin_addr.s_addr = htonl(INADDR_ANY);
  578. //绑定socket
  579. if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < )
  580. error_die("bind");
  581. //如果端口没有设置,提供个随机端口
  582. if (*port == ) /* if dynamically allocating a port */
  583. {
  584. socklen_t namelen = sizeof(name);
  585. if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -)
  586. error_die("getsockname");
  587. *port = ntohs(name.sin_port);
  588. }
  589. //监听
  590. if (listen(httpd, ) < )
  591. error_die("listen");
  592. return(httpd);
  593. }
  594.  
  595. /**********************************************************************/
  596. /* Inform the client that the requested web method has not been
  597. * implemented.
  598. * Parameter: the client socket */
  599. /**********************************************************************/
  600.  
  601. //如果方法没有实现,就返回此信息
  602. void unimplemented(int client)
  603. {
  604. char buf[];
  605.  
  606. sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
  607. send(client, buf, strlen(buf), );
  608. sprintf(buf, SERVER_STRING);
  609. send(client, buf, strlen(buf), );
  610. sprintf(buf, "Content-Type: text/html\r\n");
  611. send(client, buf, strlen(buf), );
  612. sprintf(buf, "\r\n");
  613. send(client, buf, strlen(buf), );
  614. sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
  615. send(client, buf, strlen(buf), );
  616. sprintf(buf, "</TITLE></HEAD>\r\n");
  617. send(client, buf, strlen(buf), );
  618. sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n");
  619. send(client, buf, strlen(buf), );
  620. sprintf(buf, "</BODY></HTML>\r\n");
  621. send(client, buf, strlen(buf), );
  622. }
  623.  
  624. /**********************************************************************/
  625.  
  626. int main(void)
  627. {
  628. int server_sock = -;
  629. u_short port = ;
  630. int client_sock = -;
  631. struct sockaddr_in client_name;
  632.  
  633. //这边要为socklen_t类型
  634. socklen_t client_name_len = sizeof(client_name);
  635. pthread_t newthread;
  636.  
  637. server_sock = startup(&port);
  638. printf("httpd running on port %d\n", port);
  639.  
  640. while ()
  641. {
  642. //接受请求,函数原型
  643. //#include <sys/types.h>
  644. //#include <sys/socket.h>
  645. //int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
  646. client_sock = accept(server_sock,
  647. (struct sockaddr *)&client_name,
  648. &client_name_len);
  649. if (client_sock == -)
  650. error_die("accept");
  651. /* accept_request(client_sock); */
  652.  
  653. //每次收到请求,创建一个线程来处理接受到的请求
  654. //把client_sock转成地址作为参数传入pthread_create
  655. if (pthread_create(&newthread, NULL, (void *)accept_request, (void *)(intptr_t)client_sock) != )
  656. perror("pthread_create");
  657. }
  658.  
  659. close(server_sock);
  660.  
  661. return();
  662. }

Tinyhttpd精读解析的更多相关文章

  1. TinyHttpd代码解析

    十一假期,闲来无事.看了几个C语言开源代码.http://www.cnblogs.com/TinyHttpd 这里本来想解析一下TinyHttpd的代码,但是在网上一搜,发现前辈们已经做的很好了.这里 ...

  2. 精读《V8 引擎 Lazy Parsing》

    1. 引言 本周精读的文章是 V8 引擎 Lazy Parsing,看看 V8 引擎为了优化性能,做了怎样的尝试吧! 这篇文章介绍的优化技术叫 preparser,是通过跳过不必要函数编译的方式优化性 ...

  3. Python:Sqlmap源码精读之解析xml

    XML <?xml version="1.0" encoding="UTF-8"?> <root> <!-- MySQL --&g ...

  4. .net core 源码解析-web app是如何启动并接收处理请求

    最近.net core 1.1也发布了,蹒跚学步的小孩又长高了一些,园子里大家也都非常积极的在学习,闲来无事,扒拔源码,涨涨见识. 先来见识一下web站点是如何启动的,如何接受请求,.net core ...

  5. tinyhttpd源码分析

    我们经常使用网页,作为开发人员我们也部署过httpd服务器,比如开源的apache,也开发过httpd后台服务,比如fastcgi程序,不过对于httpd服务器内部的运行机制,却不是非常了解,前几天看 ...

  6. tinyhttpd服务器源码学习

    下载地址:http://sourceforge.net/projects/tinyhttpd/ /* J. David's webserver */ /* This is a simple webse ...

  7. HTTP服务器的本质:tinyhttpd源码分析及拓展

    已经有一个月没有更新博客了,一方面是因为平时太忙了,另一方面是想积攒一些干货进行分享.最近主要是做了一些开源项目的源码分析工作,有c项目也有python项目,想提升一下内功,今天分享一下tinyhtt ...

  8. 开源代码学习之Tinyhttpd

    想开始陆续研究一些感兴趣的开源代码于是先挑一个代码量短的来过渡一下,写这篇博客的目的是记录下自己学习的过程.Tinyhttpd算是一个微型的web服务器,浏览器与Web服务器之间的通信采用的是Http ...

  9. 精读《syntax-parser 源码》

    1. 引言 syntax-parser 是一个 JS 版语法解析器生成器,具有分词.语法树解析的能力. 通过两个例子介绍它的功能. 第一个例子是创建一个词法解析器 myLexer: import { ...

随机推荐

  1. Dice (II) (DP)唉,当时没做出来

    Dice (II) Time Limit: 3000MS   Memory Limit: 32768KB   64bit IO Format: %lld & %llu [Submit]   [ ...

  2. Day2 python基础学习

    http://www.pythondoc.com/ Python中文学习大本营 本节内容: 一.字符串操作 二.列表操作 三.元组操作 四.字典操作 五.集合操作 六.字符编码操作 一.字符串操作 1 ...

  3. javascript中的DOM介绍(一)

    一.基础知识点 1.DOM是文档对象模型,是针对HTML和XML文档的一个API(应用程序接口) 2.DOM描绘了一个层次化的节点数,允许开发人员进行添加,移除个修改等操作 3.IE浏览器中所有的DO ...

  4. JAVA提高二:枚举

    JDK5.0中有一个非常有用的特性:枚举,这个特性以前在C语言中出现过,后来JDK出现后,开始觉得没有必要,但随着使用JAVA语言的人数增多,发现大家对枚举的需求非常大,于是又加入了此特性,下面我们来 ...

  5. 浅析php curl_multi_*系列函数进行批量http请求

    何起: 一系列 数量很大 数据不热 还希望被蜘蛛大量抓取的页面,在蜘蛛抓取高峰时,响应时间会被拉得很高. 前人做了这样一个事儿:页面分3块,用3个内部接口提供,入口文件用curl_multi_*系列函 ...

  6. sqlDependency监控数据库数据变化,自动通知

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  7. 将 C# 枚举反序列化为 JSON 字符串 基础理论

    该转换过程需要引用 Newtonsoft.JSON,这其中的转换过程还是蛮有意思的. 一.定义枚举 /// <summary> /// 托寄物品枚举 /// </summary> ...

  8. win10 uwp 后台获取资源

    本文告诉大家,从后台代码获取界面定义的资源. 如果一个资源是写在 App 的资源,那么如何使用代码去获得他? 简单的方法是使用下面的代码 Application.Current.Resources[& ...

  9. Linux-Nand Flash驱动(分析MTD层并制作NAND驱动)

    1.本节使用的nand flash型号为K9F2G08U0M,它的命令如下: 1.1我们以上图的read id(读ID)为例,它的时序图如下: 首先需要使能CE片选 1)使能CLE 2)发送0X90命 ...

  10. 使用Xmanager通过XDMCP连接远程Centos 7 (摘自xmanager官方博客)

    Using Xmanager to connect to remote CentOS 7 via XDMCP Gnome in CentOS 7 tries to use local hardware ...