Linux高并发web服务器开发 【转载】 include

一、HTML

1. HTML简介

(1)HTML简介

  • HTML,Hyper Texture Markup Language,超文本标记语言。
  • 在计算机中以.html、.htm作为扩展名。
  • 可以被浏览器访问, 就是经常见到的网页。

(2)HTML特点

  • 语法非常简洁、比较松散,以相应的英语单词关键字进行组合
  • html标签不区分大小写
  • 大多数标签是成对出现的, 有开始, 有结束,比如<html></html>
  • 不成对出现的称之为短标签,比如<br/> <hr/>

(3)标签中的属性和属性值

    属性="属性值"

  •  <font color="red">hello, world</font>
  • 属性值建议加引号, (双, 单引号, 不加都可以)

(4)html组成部分

  • <!doctype html> 声明文档类型
  • <html>文档的头部好和主体内容 </html> 根标记
  • <head> 文档的头部信息</head> 头部标记 只能有一对
  • <title>显示在浏览器窗口的标题栏中“网页名称”</title> 位于<head>标记之内
  • <body></body> 主体标记位于<html>之内,<head>标记之后

 示例:

Linux高并发web服务器开发 【转载】
include <stdio.h>
<html> 
<head>
    <title>这是一个标题</title>
</head>

<body>
<font color="red" size="5">hello, world</font>
</body>
</html>

Linux高并发web服务器开发 【转载】
include <stdio.h>

(5)注释

    <!-- 我是一个html注释 -->

2. 文字和标题标签

(1)标题标签

  • <h1></h1> // 最大

          只有一个
          搜索引擎优化:seo

  • <h2></h2>
  • ...
  • <h6></h6> // 最小
  • 1-6依次变小, 自动换行

(2)文本标签

  • <font></font>

     属性: 
            color: 文字颜色
                   表示方式:
                   英文单词: red green blue......
                   使用16进制的形式表示颜色: #ffffff -- (rgb)
                   使用rgb(255, 255, 0)
            size: 文字大小
                    范围 1 -- 7
                    7最大
                    1最小

(3)文本格式化标签

  • 文本加粗标签

          <strong></strong>
          <b></b>
         工作里尽量使用strong

  • 文本倾斜标签

         <em></em>
         <i></i>
         工作里尽量使用em

  • 删除线标签

         <del></del>
         <s></s>
         工作里尽量使用del

  • 下划线标签(插入文本)

         <ins></ins>
         <u></u>
        工作里尽量ins

(4)段落

  • <p>xxx</p>

          特点:
                上下自动生成空白行

(5)块容器

  • <div>This is a div element.</div>
  • 用于没有语义含义的内容的块级容器(或网页的"划分")。
  • 属性:对齐方式

          align:
                 left
                 center
                 right

(6)换行

  • <br/>

(7)水平线

  • <hr/>

          属性:
                 color: 3种表示方法
                 size: 1-7
                例如:<hr color="red" size="3"/>

3. 列表标签

(1)无序列表
         标签:

<ul>
    <li></li> 列表项
    <li></li>
</ul>

         属性:type

                   实心圆圈: disc -- 默认
                   空心圆圈: circle
                   小方块: square

(2)有序列表

         标签:

<ol>
    <li></li> 列表项
    <li></li>
</ol>

         属性:

  • type -- 序号

          1 -- 默认
          a
          A
           i -- 罗马数字(小)
           I -- 罗马数字(大)

  • start

          从序号的什么位置开始表示

(3)自定义列表
         标签

<dl>
    <dt></dt> 小标题
    <dd></dd> 解释标题
    <dd></dd> 解释标题
</dl>

4. 图片标签

  • 属性:

          src: 图片的来源 必写属性
          alt: 替换文本 图片不显示的时候显示的文字
          title: 提示文本 鼠标放到图片上显示的文字
          图片宽度
          height: 图片高度

  • 注意:

          图片没有定义宽高的时候,图片按照百分之百比例显示
          如果只更改图片的宽度或者高度,图片等比例缩放。

示例:

<img src="3.gif" alt="小岳岳" title="我的天呐!" width="300" height="200" />

5. 超链接标签

(1)超链接标签

         <a href="http://jd.com" title="A dog" target="_blank">超链接</a>
    属性:
          href: 去往的路径(跳转的页面)必写属性
          title: 提示文本, 鼠标放到链接上显示的文字
          target:
                 _self:默认值 在自身页面打开(关闭自身页面,打开链接页面)
                 _blank: 打开新页面 (自身页面不关闭,打开一个新的链接页面)
    示例:

 <a href="http://www.baidu.com">百度一下</a>

(2)锚链接

  • 先定义一个锚点: <p >
  • 超链接到锚点: <a herf="#sd">回到顶点</a>

(6)表格标签

  • <table></table>

      属性:
            border -- 表格线, 宽度1-7
            bordercolor -- 表格线颜色
            width
            height

  • <tr> -- 行

      属性:
            align -- 对齐方式:
                center
                left
                right

  • <td> -- 单元格(列)

          对其属性设置同tr

示例:

Linux高并发web服务器开发 【转载】
include <stdio.h>
<table border=>
<tr>
    <td></td> 第一列
    <td></td> 第二列
</tr>

<tr>
<td></td>
<td></td>
</tr>

<tr>
<td></td>
<td></td>
</tr>
</table>

Linux高并发web服务器开发 【转载】
include <stdio.h>

二、http协议 - 应用层

1. 请求消息(Request) - 浏览器给服务器发

   四部分: 请求行, 请求头, 空行, 请求数据

  • 请求行: 说明请求类型, 要访问的资源, 以及使用的http版本
  • 请求头: 说明服务器要使用的附加信息
  • 空行: 空行是必须要有的, 即使没有请求数据
  • 请求数据: 也叫主体, 可以添加任意的其他数据

示例:

Linux高并发web服务器开发 【转载】
include <stdio.h>
GET /3.txt HTTP/1.1
    /: 资源目录的根目录
    三部分内容由空格间隔
Host: localhost:2222
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/201001 01 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-Modified-Since: Fri, 18 Jul 2014 08:36:36 GMT
    请求头:由键值对构成的

请求数据
换行:

Linux高并发web服务器开发 【转载】
include <stdio.h>

2. 响应消息(Response) - 服务器给浏览器发  

    四部分: 状态行, 消息报头, 空行, 响应正文

  • 状态行: 包括http协议版本号, 状态码, 状态信息
  • 消息报头: 说明客户端要使用的一些附加信息
  • 空行: 空行是必须要有的
  • 响应正文: 服务器返回给客户端的文本信息

示例:

Linux高并发web服务器开发 【转载】
include <stdio.h>
HTTP/1.1 200 Ok
Server: micro_httpd
Date: Fri, 18 Jul 2014 14:34:26 GMT
Content-Type: text/plain; charset=iso-8859-1 (必选项)
    告诉浏览器发送的数据是什么类型
Content-Length: 32 
    发送的数据的长度
Content-Language: zh-CN
Last-Modified: Fri, 18 Jul 2014 08:36:36 GMT
Connection: close

int main(void)
{
printf("hello world! ");
return 0;
}

Linux高并发web服务器开发 【转载】
include <stdio.h>

3. HTTP1.1的五种请求方法

1)GET

      请求指定的页面信息,并返回实体主体。

2)POST

      向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST请求可能会导致新的资源的建立和/或已有资源的修改。

3)HEAD 

     类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头。

4)PUT

     从客户端向服务器传送的数据取代指定的文档的内容。

5)DELETE

     请求服务器删除指定的页面。

6)CONNECT

    HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。

7)OPTIONS

    允许客户端查看服务器的性能。

8)TRACE

    回显服务器收到的请求,主要用于测试或诊断。

示例:http使用get和post请求数据

  • 使用get方法请求数据:
Linux高并发web服务器开发 【转载】
include <stdio.h>
GET /3.txt HTTP/1.1
Host: localhost:2222
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/201001    01 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-Modified-Since: Fri, 18 Jul 2014 08:36:36 GMT

空行
请求数据(可以为空)
Linux高并发web服务器开发 【转载】
include <stdio.h>
  • 使用post方法请求数据:
Linux高并发web服务器开发 【转载】
include <stdio.h>
POST  HTTP/1.1
Host: localhost:2222
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/201001    01 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-Modified-Since: Fri, 18 Jul 2014 08:36:36 GMT
空行
username=jack&pwd=123456&sex=男
Linux高并发web服务器开发 【转载】
include <stdio.h>
  • 浏览器地址栏:
Linux高并发web服务器开发 【转载】
include <stdio.h>
192.168.30.131/hello.c
浏览器封装一个http请求协议
get /hello.c http/1.1
key:value
key:value
key:value
key:value

Linux高并发web服务器开发 【转载】
include <stdio.h>

4. HTTP常用状态码

    状态代码有三位数字组成,第一个数字定义了响应的类别,共分五种类别:

  • 1xx:指示信息--表示请求已接收,继续处理
  • 2xx:成功--表示请求已被成功接收、理解、接受
  • 3xx:重定向--要完成请求必须进行更进一步的操作
  • 4xx:客户端错误--请求有语法错误或请求无法实现
  • 5xx:服务器端错误--服务器未能实现合法的请求

    常见状态码:

Linux高并发web服务器开发 【转载】
include <stdio.h>
200 OK 客户端请求成功
400 Bad Request 客户端请求有语法错误,不能被服务器所理解
401 Unauthorized 请求未经授权,这个状态代码必须和WWW-Authenticate报头域一起使用 
403 Forbidden 服务器收到请求,但是拒绝提供服务
404 Not Found 请求资源不存在,eg:输入了错误的URL
500 Internal Server Error 服务器发生不可预期的错误
503 Server Unavailable 服务器当前不能处理客户端的请求,一段时间后可能恢复正常
Linux高并发web服务器开发 【转载】
include <stdio.h>

5. http中的文件类型

Linux高并发web服务器开发 【转载】
include <stdio.h>
普通文件: text/plain; charset=utf-8
*.html     : text/html; charset=utf-8
*.jpg    : image/jpeg
*.gif    : image/gif
*.png    : image/png
*.wav    : audio/wav
*.avi    : video/x-msvideo
*.mov    : video/quicktime
*.mp3    : audio/mpeg

charset=iso-8859-1 西欧的编码,说明网站采用的编码是英文;
charset=gb2312 说明网站采用的编码是简体中文;
charset=utf-8 代表世界通用的语言编码;
可以用到中文、韩文、日文等世界上所有语言编码上
charset=euc-kr 说明网站采用的编码是韩文;
charset=big5 说明网站采用的编码是繁体中文;

Linux高并发web服务器开发 【转载】
include <stdio.h>

6. 重定向

Linux高并发web服务器开发 【转载】
include <stdio.h>

三、web服务器实现

1. 实现思路

(1)编写函数解析http请求

    GET /hello.html HTTP/1.1

    将上述字符串分为三部分解析出来

(2)编写函数根据文件后缀,返回对应的文件类型

(3)sscanf - 读取格式化的字符串中的数据

    使用正则表达式拆分
    [^ ]的用法

(4)通过浏览器请求目录数据

  • 读指定目录内容
opendir
readdir
closedir
  • scandir - 扫描dir目录下(不包括子目录)内容
Linux高并发web服务器开发 【转载】
include <stdio.h>
#include <dirent.h>

int scandir(const char *dirp,
struct dirent **namelist,
int (
filter)(const struct dirent ),
int (
compar)(const struct dirent **, const struct dirent **)
);

dirp
- 当前要扫描的目录
namelist
- struct dirent** ptr;
- struct dirent* ptr[];
- &ptr;
filter
- NULL
compar
文件名显示的时候, 指定排序规则
- alphasort
- versionsort

Linux高并发web服务器开发 【转载】
include <stdio.h>

(5)http中数据特殊字符编码解码问题

    编码
    解码

服务器端伪代码:

Linux高并发web服务器开发 【转载】
include <stdio.h>
 1 void http_respond_head(int cfd, char* type)
 2 {
 3     char buf[1024];
 4     // 状态行
 5     sprintf(buf, "http/1.1 200 OK
");
 6     write(cfd, buf, strlen(buf));
 7     // 消息报头
 8     sprintf(buf, "Content-Type: %s
", type);
 9     write(cfd, buf, strlen(buf));
10     
11     // 空行
12     write(cfd, "
", 2);
13 }
14 
15 void main()
16 {
17     // 修改进程的工作目录
18     chdir(path);
19     // 创建监听的套接字
20     int lfd = socket(af_inet, sock_stream, 0);
21     // 绑定
22     struct sockaddr_in serv;
23     serv.family = af_inet;
24     serv.port = htons(8989);
25     bind(lfd, &serv, len);
26     // 监听
27     listen();
28     
29     int cfd = accept();
30     // 读数据
31     read(cfd, buf, sizeof(buf));
32     // 先将buf中的请求行拿出来
33     // GET /hello.c http/1.1
34     char method[12], path[1024], protocol[12];
35     // 得到文件名
36     char* file = path+1;
37     // 打开文件
38     int fdd = open(file, O_RDONLY);
39     int len = 0;
40     http_respond_head(cfd, "text/plain");
41     // 循环读数据
42     while( (len=read(fdd, buf, sizeof(buf))) > 0)
43     {
44         // 数据发送给浏览器
45         write(fdd, buf, len));
46     }
47 }
Linux高并发web服务器开发 【转载】
include <stdio.h>

2. 服务器端代码实现

    实现的是从浏览器输入比如:192.168.30.131:8000/home,服务端会将/home目录下的文件及文件夹返回到浏览器。

    版本1:

Linux高并发web服务器开发 【转载】
include <stdio.h>
  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <stdlib.h>
  4 #include <sys/types.h>
  5 #include <string.h>
  6 #include <sys/epoll.h>
  7 #include <arpa/inet.h>
  8 #include <fcntl.h>
  9 #include <dirent.h>
 10 #include <sys/stat.h>
 11 #include <ctype.h>
 12 #include "epoll_server.h"
 13 
 14 #define MAXSIZE 2000
 15 
 16 void epoll_run(int port)
 17 {
 18     // 创建一个epoll树的根节点
 19     int epfd = epoll_create(MAXSIZE);
 20     if(epfd == -1)
 21     {
 22         perror("epoll_create error");
 23         exit(1);
 24     }
 25 
 26     // 添加要监听的节点
 27     // 先添加监听lfd
 28     int lfd = init_listen_fd(port, epfd);
 29 
 30     // 委托内核检测添加到树上的节点
 31     struct epoll_event all[MAXSIZE];
 32     while(1)
 33     {
 34         int ret = epoll_wait(epfd, all, MAXSIZE, -1);
 35         if(ret == -1)
 36         {
 37             perror("epoll_wait error");
 38             exit(1);
 39         }
 40 
 41         // 遍历发生变化的节点
 42         for(int i=0; i<ret; ++i)
 43         {
 44             // 只处理读事件, 其他事件默认不处理
 45             struct epoll_event *pev = &all[i];
 46             if(!(pev->events & EPOLLIN))
 47             {
 48                 // 不是读事件
 49                 continue;
 50             }
 51 
 52             if(pev->data.fd == lfd)
 53             {
 54                 // 接受连接请求
 55                 do_accept(lfd, epfd);
 56             }
 57             else
 58             {
 59                 // 读数据
 60                 do_read(pev->data.fd, epfd);
 61             }
 62         }
 63     }
 64 }
 65 
 66 // 读数据
 67 void do_read(int cfd, int epfd)
 68 {
 69     // 将浏览器发过来的数据, 读到buf中 
 70     char line[1024] = {0};
 71     // 读请求行
 72     int len = get_line(cfd, line, sizeof(line));
 73     if(len == 0)
 74     {
 75         printf("客户端断开了连接...
");
 76         // 关闭套接字, cfd从epoll上del
 77         disconnect(cfd, epfd);         
 78     }
 79     else
 80     {
 81         printf("请求行数据: %s", line);
 82         printf("============= 请求头 ============
");
 83         // 还有数据没读完
 84         // 继续读
 85         while(len)
 86         {
 87             char buf[1024] = {0};
 88             len = get_line(cfd, buf, sizeof(buf));
 89             printf("-----: %s", buf);
 90         }
 91         printf("============= The End ============
");
 92     }
 93 
 94     // 请求行: get /xxx http/1.1
 95     // 判断是不是get请求
 96     if(strncasecmp("get", line, 3) == 0)
 97     {
 98         // 处理http请求
 99         http_request(line, cfd);
100         // 关闭套接字, cfd从epoll上del
101         disconnect(cfd, epfd);         
102     }
103 }
104 
105 // 断开连接的函数
106 void disconnect(int cfd, int epfd)
107 {
108     int ret = epoll_ctl(epfd, EPOLL_CTL_DEL, cfd, NULL);
109     if(ret == -1)
110     {
111         perror("epoll_ctl del cfd error");
112         exit(1);
113     }
114     close(cfd);
115 }
116 
117 // http请求处理
118 void http_request(const char* request, int cfd)
119 {
120     // 拆分http请求行
121     // get /xxx http/1.1
122     char method[12], path[1024], protocol[12];
123     sscanf(request, "%[^ ] %[^ ] %[^ ]", method, path, protocol);
124 
125     printf("method = %s, path = %s, protocol = %s
", method, path, protocol);
126 
127     // 转码 将不能识别的中文乱码 - > 中文
128     // 解码 %23 %34 %5f
129     decode_str(path, path);
130         // 处理path  /xx
131         // 去掉path中的/
132         char* file = path+1;
133     // 如果没有指定访问的资源, 默认显示资源目录中的内容
134     if(strcmp(path, "/") == 0)
135     {
136         // file的值, 资源目录的当前位置
137         file = "./";
138     }
139 
140     // 获取文件属性
141     struct stat st;
142     int ret = stat(file, &st);
143     if(ret == -1)
144     {
145         // show 404
146         send_respond_head(cfd, 404, "File Not Found", ".html", -1);
147         send_file(cfd, "404.html");
148     }
149 
150     // 判断是目录还是文件
151     // 如果是目录
152     if(S_ISDIR(st.st_mode))
153     {
154         // 发送头信息
155         send_respond_head(cfd, 200, "OK", get_file_type(".html"), -1);
156         // 发送目录信息
157         send_dir(cfd, file);
158     }
159     else if(S_ISREG(st.st_mode))
160     {
161         // 文件
162         // 发送消息报头
163         send_respond_head(cfd, 200, "OK", get_file_type(file), st.st_size);
164         // 发送文件内容
165         send_file(cfd, file);
166     }
167 }
168 
169 // 发送目录内容
170 void send_dir(int cfd, const char* dirname)
171 {
172     // 拼一个html页面<table></table>
173     char buf[4094] = {0};
174 
175     sprintf(buf, "<html><head><title>目录名: %s</title></head>", dirname);
176     sprintf(buf+strlen(buf), "<body><h1>当前目录: %s</h1><table>", dirname);
177 
178     char enstr[1024] = {0};
179     char path[1024] = {0};
180     // 目录项二级指针
181     struct dirent** ptr;
182     int num = scandir(dirname, &ptr, NULL, alphasort);
183     // 遍历
184     for(int i=0; i<num; ++i)
185     {
186         char* name = ptr[i]->d_name;
187 
188         // 拼接文件的完整路径
189         sprintf(path, "%s/%s", dirname, name);
190         printf("path = %s ===================
", path);
191         struct stat st;
192         stat(path, &st);
193 
194         encode_str(enstr, sizeof(enstr), name);
195         // 如果是文件
196         if(S_ISREG(st.st_mode))
197         {
198             sprintf(buf+strlen(buf), 
199                     "<tr><td><a href="%s">%s</a></td><td>%ld</td></tr>",
200                     enstr, name, (long)st.st_size);
201         }
202         // 如果是目录
203         else if(S_ISDIR(st.st_mode))
204         {
205             sprintf(buf+strlen(buf), 
206                     "<tr><td><a href="%s/">%s/</a></td><td>%ld</td></tr>",
207                     enstr, name, (long)st.st_size);
208         }
209         send(cfd, buf, strlen(buf), 0);
210         memset(buf, 0, sizeof(buf));
211         // 字符串拼接
212     }
213 
214     sprintf(buf+strlen(buf), "</table></body></html>");
215     send(cfd, buf, strlen(buf), 0);
216 
217     printf("dir message send OK!!!!
");
218 #if 0
219     // 打开目录
220     DIR* dir = opendir(dirname);
221     if(dir == NULL)
222     {
223         perror("opendir error");
224         exit(1);
225     }
226 
227     // 读目录
228     struct dirent* ptr = NULL;
229     while( (ptr = readdir(dir)) != NULL )
230     {
231         char* name = ptr->d_name;
232     }
233     closedir(dir);
234 #endif
235 }
236 
237 // 发送响应头
238 void send_respond_head(int cfd, int no, const char* desp, const char* type, long len)
239 {
240     char buf[1024] = {0};
241     // 状态行
242     sprintf(buf, "http/1.1 %d %s
", no, desp);
243     send(cfd, buf, strlen(buf), 0);
244     // 消息报头
245     sprintf(buf, "Content-Type:%s
", type);
246     sprintf(buf+strlen(buf), "Content-Length:%ld
", len);
247     send(cfd, buf, strlen(buf), 0);
248     // 空行
249     send(cfd, "
", 2, 0);
250 }
251 
252 // 发送文件
253 void send_file(int cfd, const char* filename)
254 {
255     // 打开文件
256     int fd = open(filename, O_RDONLY);
257     if(fd == -1)
258     {
259         // show 404
260         return;
261     }
262 
263     // 循环读文件
264     char buf[4096] = {0};
265     int len = 0;
266     while( (len = read(fd, buf, sizeof(buf))) > 0 )
267     {
268         // 发送读出的数据
269         send(cfd, buf, len, 0);
270     }
271     if(len == -1)
272     {
273         perror("read file error");
274         exit(1);
275     }
276 
277     close(fd);
278 }
279 
280 // 解析http请求消息的每一行内容
281 int get_line(int sock, char *buf, int size)
282 {
283     int i = 0;
284     char c = '

一、HTML

1. HTML简介

(1)HTML简介

  • HTML,Hyper Texture Markup Language,超文本标记语言。
  • 在计算机中以.html、.htm作为扩展名。
  • 可以被浏览器访问, 就是经常见到的网页。

(2)HTML特点

  • 语法非常简洁、比较松散,以相应的英语单词关键字进行组合
  • html标签不区分大小写
  • 大多数标签是成对出现的, 有开始, 有结束,比如<html></html>
  • 不成对出现的称之为短标签,比如<br/> <hr/>

(3)标签中的属性和属性值

    属性="属性值"

  •  <font color="red">hello, world</font>
  • 属性值建议加引号, (双, 单引号, 不加都可以)

(4)html组成部分

  • <!doctype html> 声明文档类型
  • <html>文档的头部好和主体内容 </html> 根标记
  • <head> 文档的头部信息</head> 头部标记 只能有一对
  • <title>显示在浏览器窗口的标题栏中“网页名称”</title> 位于<head>标记之内
  • <body></body> 主体标记位于<html>之内,<head>标记之后

 示例:

Linux高并发web服务器开发 【转载】
include <stdio.h>
<html> 
<head>
    <title>这是一个标题</title>
</head>

<body>
<font color="red" size="5">hello, world</font>
</body>
</html>

Linux高并发web服务器开发 【转载】
include <stdio.h>

(5)注释

    <!-- 我是一个html注释 -->

2. 文字和标题标签

(1)标题标签

  • <h1></h1> // 最大

          只有一个
          搜索引擎优化:seo

  • <h2></h2>
  • ...
  • <h6></h6> // 最小
  • 1-6依次变小, 自动换行

(2)文本标签

  • <font></font>

     属性: 
            color: 文字颜色
                   表示方式:
                   英文单词: red green blue......
                   使用16进制的形式表示颜色: #ffffff -- (rgb)
                   使用rgb(255, 255, 0)
            size: 文字大小
                    范围 1 -- 7
                    7最大
                    1最小

(3)文本格式化标签

  • 文本加粗标签

          <strong></strong>
          <b></b>
         工作里尽量使用strong

  • 文本倾斜标签

         <em></em>
         <i></i>
         工作里尽量使用em

  • 删除线标签

         <del></del>
         <s></s>
         工作里尽量使用del

  • 下划线标签(插入文本)

         <ins></ins>
         <u></u>
        工作里尽量ins

(4)段落

  • <p>xxx</p>

          特点:
                上下自动生成空白行

(5)块容器

  • <div>This is a div element.</div>
  • 用于没有语义含义的内容的块级容器(或网页的"划分")。
  • 属性:对齐方式

          align:
                 left
                 center
                 right

(6)换行

  • <br/>

(7)水平线

  • <hr/>

          属性:
                 color: 3种表示方法
                 size: 1-7
                例如:<hr color="red" size="3"/>

3. 列表标签

(1)无序列表
         标签:

<ul>
    <li></li> 列表项
    <li></li>
</ul>

         属性:type

                   实心圆圈: disc -- 默认
                   空心圆圈: circle
                   小方块: square

(2)有序列表

         标签:

<ol>
    <li></li> 列表项
    <li></li>
</ol>

         属性:

  • type -- 序号

          1 -- 默认
          a
          A
           i -- 罗马数字(小)
           I -- 罗马数字(大)

  • start

          从序号的什么位置开始表示

(3)自定义列表
         标签

<dl>
    <dt></dt> 小标题
    <dd></dd> 解释标题
    <dd></dd> 解释标题
</dl>

4. 图片标签

  • 属性:

          src: 图片的来源 必写属性
          alt: 替换文本 图片不显示的时候显示的文字
          title: 提示文本 鼠标放到图片上显示的文字
          图片宽度
          height: 图片高度

  • 注意:

          图片没有定义宽高的时候,图片按照百分之百比例显示
          如果只更改图片的宽度或者高度,图片等比例缩放。

示例:

<img src="3.gif" alt="小岳岳" title="我的天呐!" width="300" height="200" />

5. 超链接标签

(1)超链接标签

         <a href="http://jd.com" title="A dog" target="_blank">超链接</a>
    属性:
          href: 去往的路径(跳转的页面)必写属性
          title: 提示文本, 鼠标放到链接上显示的文字
          target:
                 _self:默认值 在自身页面打开(关闭自身页面,打开链接页面)
                 _blank: 打开新页面 (自身页面不关闭,打开一个新的链接页面)
    示例:

 <a href="http://www.baidu.com">百度一下</a>

(2)锚链接

  • 先定义一个锚点: <p >
  • 超链接到锚点: <a herf="#sd">回到顶点</a>

(6)表格标签

  • <table></table>

      属性:
            border -- 表格线, 宽度1-7
            bordercolor -- 表格线颜色
            width
            height

  • <tr> -- 行

      属性:
            align -- 对齐方式:
                center
                left
                right

  • <td> -- 单元格(列)

          对其属性设置同tr

示例:

Linux高并发web服务器开发 【转载】
include <stdio.h>
<table border=>
<tr>
    <td></td> 第一列
    <td></td> 第二列
</tr>

<tr>
<td></td>
<td></td>
</tr>

<tr>
<td></td>
<td></td>
</tr>
</table>

Linux高并发web服务器开发 【转载】
include <stdio.h>

二、http协议 - 应用层

1. 请求消息(Request) - 浏览器给服务器发

   四部分: 请求行, 请求头, 空行, 请求数据

  • 请求行: 说明请求类型, 要访问的资源, 以及使用的http版本
  • 请求头: 说明服务器要使用的附加信息
  • 空行: 空行是必须要有的, 即使没有请求数据
  • 请求数据: 也叫主体, 可以添加任意的其他数据

示例:

Linux高并发web服务器开发 【转载】
include <stdio.h>
GET /3.txt HTTP/1.1
    /: 资源目录的根目录
    三部分内容由空格间隔
Host: localhost:2222
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/201001 01 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-Modified-Since: Fri, 18 Jul 2014 08:36:36 GMT
    请求头:由键值对构成的

请求数据
换行:

Linux高并发web服务器开发 【转载】
include <stdio.h>

2. 响应消息(Response) - 服务器给浏览器发  

    四部分: 状态行, 消息报头, 空行, 响应正文

  • 状态行: 包括http协议版本号, 状态码, 状态信息
  • 消息报头: 说明客户端要使用的一些附加信息
  • 空行: 空行是必须要有的
  • 响应正文: 服务器返回给客户端的文本信息

示例:

Linux高并发web服务器开发 【转载】
include <stdio.h>
HTTP/1.1 200 Ok
Server: micro_httpd
Date: Fri, 18 Jul 2014 14:34:26 GMT
Content-Type: text/plain; charset=iso-8859-1 (必选项)
    告诉浏览器发送的数据是什么类型
Content-Length: 32 
    发送的数据的长度
Content-Language: zh-CN
Last-Modified: Fri, 18 Jul 2014 08:36:36 GMT
Connection: close

int main(void)
{
printf("hello world! ");
return 0;
}

Linux高并发web服务器开发 【转载】
include <stdio.h>

3. HTTP1.1的五种请求方法

1)GET

      请求指定的页面信息,并返回实体主体。

2)POST

      向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST请求可能会导致新的资源的建立和/或已有资源的修改。

3)HEAD 

     类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头。

4)PUT

     从客户端向服务器传送的数据取代指定的文档的内容。

5)DELETE

     请求服务器删除指定的页面。

6)CONNECT

    HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。

7)OPTIONS

    允许客户端查看服务器的性能。

8)TRACE

    回显服务器收到的请求,主要用于测试或诊断。

示例:http使用get和post请求数据

  • 使用get方法请求数据:
Linux高并发web服务器开发 【转载】
include <stdio.h>
GET /3.txt HTTP/1.1
Host: localhost:2222
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/201001    01 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-Modified-Since: Fri, 18 Jul 2014 08:36:36 GMT

空行
请求数据(可以为空)
Linux高并发web服务器开发 【转载】
include <stdio.h>
  • 使用post方法请求数据:
Linux高并发web服务器开发 【转载】
include <stdio.h>
POST  HTTP/1.1
Host: localhost:2222
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/201001    01 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-Modified-Since: Fri, 18 Jul 2014 08:36:36 GMT
空行
username=jack&pwd=123456&sex=男
Linux高并发web服务器开发 【转载】
include <stdio.h>
  • 浏览器地址栏:
Linux高并发web服务器开发 【转载】
include <stdio.h>
192.168.30.131/hello.c
浏览器封装一个http请求协议
get /hello.c http/1.1
key:value
key:value
key:value
key:value

Linux高并发web服务器开发 【转载】
include <stdio.h>

4. HTTP常用状态码

    状态代码有三位数字组成,第一个数字定义了响应的类别,共分五种类别:

  • 1xx:指示信息--表示请求已接收,继续处理
  • 2xx:成功--表示请求已被成功接收、理解、接受
  • 3xx:重定向--要完成请求必须进行更进一步的操作
  • 4xx:客户端错误--请求有语法错误或请求无法实现
  • 5xx:服务器端错误--服务器未能实现合法的请求

    常见状态码:

Linux高并发web服务器开发 【转载】
include <stdio.h>
200 OK 客户端请求成功
400 Bad Request 客户端请求有语法错误,不能被服务器所理解
401 Unauthorized 请求未经授权,这个状态代码必须和WWW-Authenticate报头域一起使用 
403 Forbidden 服务器收到请求,但是拒绝提供服务
404 Not Found 请求资源不存在,eg:输入了错误的URL
500 Internal Server Error 服务器发生不可预期的错误
503 Server Unavailable 服务器当前不能处理客户端的请求,一段时间后可能恢复正常
Linux高并发web服务器开发 【转载】
include <stdio.h>

5. http中的文件类型

Linux高并发web服务器开发 【转载】
include <stdio.h>
普通文件: text/plain; charset=utf-8
*.html     : text/html; charset=utf-8
*.jpg    : image/jpeg
*.gif    : image/gif
*.png    : image/png
*.wav    : audio/wav
*.avi    : video/x-msvideo
*.mov    : video/quicktime
*.mp3    : audio/mpeg

charset=iso-8859-1 西欧的编码,说明网站采用的编码是英文;
charset=gb2312 说明网站采用的编码是简体中文;
charset=utf-8 代表世界通用的语言编码;
可以用到中文、韩文、日文等世界上所有语言编码上
charset=euc-kr 说明网站采用的编码是韩文;
charset=big5 说明网站采用的编码是繁体中文;

Linux高并发web服务器开发 【转载】
include <stdio.h>

6. 重定向

Linux高并发web服务器开发 【转载】
include <stdio.h>

三、web服务器实现

1. 实现思路

(1)编写函数解析http请求

    GET /hello.html HTTP/1.1

    将上述字符串分为三部分解析出来

(2)编写函数根据文件后缀,返回对应的文件类型

(3)sscanf - 读取格式化的字符串中的数据

    使用正则表达式拆分
    [^ ]的用法

(4)通过浏览器请求目录数据

  • 读指定目录内容
opendir
readdir
closedir
  • scandir - 扫描dir目录下(不包括子目录)内容
Linux高并发web服务器开发 【转载】
include <stdio.h>
#include <dirent.h>

int scandir(const char *dirp,
struct dirent **namelist,
int (
filter)(const struct dirent ),
int (
compar)(const struct dirent **, const struct dirent **)
);

dirp
- 当前要扫描的目录
namelist
- struct dirent** ptr;
- struct dirent* ptr[];
- &ptr;
filter
- NULL
compar
文件名显示的时候, 指定排序规则
- alphasort
- versionsort

Linux高并发web服务器开发 【转载】
include <stdio.h>

(5)http中数据特殊字符编码解码问题

    编码
    解码

服务器端伪代码:

Linux高并发web服务器开发 【转载】
include <stdio.h>
 1 void http_respond_head(int cfd, char* type)
 2 {
 3     char buf[1024];
 4     // 状态行
 5     sprintf(buf, "http/1.1 200 OK
");
 6     write(cfd, buf, strlen(buf));
 7     // 消息报头
 8     sprintf(buf, "Content-Type: %s
", type);
 9     write(cfd, buf, strlen(buf));
10     
11     // 空行
12     write(cfd, "
", 2);
13 }
14 
15 void main()
16 {
17     // 修改进程的工作目录
18     chdir(path);
19     // 创建监听的套接字
20     int lfd = socket(af_inet, sock_stream, 0);
21     // 绑定
22     struct sockaddr_in serv;
23     serv.family = af_inet;
24     serv.port = htons(8989);
25     bind(lfd, &serv, len);
26     // 监听
27     listen();
28     
29     int cfd = accept();
30     // 读数据
31     read(cfd, buf, sizeof(buf));
32     // 先将buf中的请求行拿出来
33     // GET /hello.c http/1.1
34     char method[12], path[1024], protocol[12];
35     // 得到文件名
36     char* file = path+1;
37     // 打开文件
38     int fdd = open(file, O_RDONLY);
39     int len = 0;
40     http_respond_head(cfd, "text/plain");
41     // 循环读数据
42     while( (len=read(fdd, buf, sizeof(buf))) > 0)
43     {
44         // 数据发送给浏览器
45         write(fdd, buf, len));
46     }
47 }
Linux高并发web服务器开发 【转载】
include <stdio.h>

2. 服务器端代码实现

    实现的是从浏览器输入比如:192.168.30.131:8000/home,服务端会将/home目录下的文件及文件夹返回到浏览器。

    版本1:

Linux高并发web服务器开发 【转载】
include <stdio.h>
  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <stdlib.h>
  4 #include <sys/types.h>
  5 #include <string.h>
  6 #include <sys/epoll.h>
  7 #include <arpa/inet.h>
  8 #include <fcntl.h>
  9 #include <dirent.h>
 10 #include <sys/stat.h>
 11 #include <ctype.h>
 12 #include "epoll_server.h"
 13 
 14 #define MAXSIZE 2000
 15 
 16 void epoll_run(int port)
 17 {
 18     // 创建一个epoll树的根节点
 19     int epfd = epoll_create(MAXSIZE);
 20     if(epfd == -1)
 21     {
 22         perror("epoll_create error");
 23         exit(1);
 24     }
 25 
 26     // 添加要监听的节点
 27     // 先添加监听lfd
 28     int lfd = init_listen_fd(port, epfd);
 29 
 30     // 委托内核检测添加到树上的节点
 31     struct epoll_event all[MAXSIZE];
 32     while(1)
 33     {
 34         int ret = epoll_wait(epfd, all, MAXSIZE, -1);
 35         if(ret == -1)
 36         {
 37             perror("epoll_wait error");
 38             exit(1);
 39         }
 40 
 41         // 遍历发生变化的节点
 42         for(int i=0; i<ret; ++i)
 43         {
 44             // 只处理读事件, 其他事件默认不处理
 45             struct epoll_event *pev = &all[i];
 46             if(!(pev->events & EPOLLIN))
 47             {
 48                 // 不是读事件
 49                 continue;
 50             }
 51 
 52             if(pev->data.fd == lfd)
 53             {
 54                 // 接受连接请求
 55                 do_accept(lfd, epfd);
 56             }
 57             else
 58             {
 59                 // 读数据
 60                 do_read(pev->data.fd, epfd);
 61             }
 62         }
 63     }
 64 }
 65 
 66 // 读数据
 67 void do_read(int cfd, int epfd)
 68 {
 69     // 将浏览器发过来的数据, 读到buf中 
 70     char line[1024] = {0};
 71     // 读请求行
 72     int len = get_line(cfd, line, sizeof(line));
 73     if(len == 0)
 74     {
 75         printf("客户端断开了连接...
");
 76         // 关闭套接字, cfd从epoll上del
 77         disconnect(cfd, epfd);         
 78     }
 79     else
 80     {
 81         printf("请求行数据: %s", line);
 82         printf("============= 请求头 ============
");
 83         // 还有数据没读完
 84         // 继续读
 85         while(len)
 86         {
 87             char buf[1024] = {0};
 88             len = get_line(cfd, buf, sizeof(buf));
 89             printf("-----: %s", buf);
 90         }
 91         printf("============= The End ============
");
 92     }
 93 
 94     // 请求行: get /xxx http/1.1
 95     // 判断是不是get请求
 96     if(strncasecmp("get", line, 3) == 0)
 97     {
 98         // 处理http请求
 99         http_request(line, cfd);
100         // 关闭套接字, cfd从epoll上del
101         disconnect(cfd, epfd);         
102     }
103 }
104 
105 // 断开连接的函数
106 void disconnect(int cfd, int epfd)
107 {
108     int ret = epoll_ctl(epfd, EPOLL_CTL_DEL, cfd, NULL);
109     if(ret == -1)
110     {
111         perror("epoll_ctl del cfd error");
112         exit(1);
113     }
114     close(cfd);
115 }
116 
117 // http请求处理
118 void http_request(const char* request, int cfd)
119 {
120     // 拆分http请求行
121     // get /xxx http/1.1
122     char method[12], path[1024], protocol[12];
123     sscanf(request, "%[^ ] %[^ ] %[^ ]", method, path, protocol);
124 
125     printf("method = %s, path = %s, protocol = %s
", method, path, protocol);
126 
127     // 转码 将不能识别的中文乱码 - > 中文
128     // 解码 %23 %34 %5f
129     decode_str(path, path);
130         // 处理path  /xx
131         // 去掉path中的/
132         char* file = path+1;
133     // 如果没有指定访问的资源, 默认显示资源目录中的内容
134     if(strcmp(path, "/") == 0)
135     {
136         // file的值, 资源目录的当前位置
137         file = "./";
138     }
139 
140     // 获取文件属性
141     struct stat st;
142     int ret = stat(file, &st);
143     if(ret == -1)
144     {
145         // show 404
146         send_respond_head(cfd, 404, "File Not Found", ".html", -1);
147         send_file(cfd, "404.html");
148     }
149 
150     // 判断是目录还是文件
151     // 如果是目录
152     if(S_ISDIR(st.st_mode))
153     {
154         // 发送头信息
155         send_respond_head(cfd, 200, "OK", get_file_type(".html"), -1);
156         // 发送目录信息
157         send_dir(cfd, file);
158     }
159     else if(S_ISREG(st.st_mode))
160     {
161         // 文件
162         // 发送消息报头
163         send_respond_head(cfd, 200, "OK", get_file_type(file), st.st_size);
164         // 发送文件内容
165         send_file(cfd, file);
166     }
167 }
168 
169 // 发送目录内容
170 void send_dir(int cfd, const char* dirname)
171 {
172     // 拼一个html页面<table></table>
173     char buf[4094] = {0};
174 
175     sprintf(buf, "<html><head><title>目录名: %s</title></head>", dirname);
176     sprintf(buf+strlen(buf), "<body><h1>当前目录: %s</h1><table>", dirname);
177 
178     char enstr[1024] = {0};
179     char path[1024] = {0};
180     // 目录项二级指针
181     struct dirent** ptr;
182     int num = scandir(dirname, &ptr, NULL, alphasort);
183     // 遍历
184     for(int i=0; i<num; ++i)
185     {
186         char* name = ptr[i]->d_name;
187 
188         // 拼接文件的完整路径
189         sprintf(path, "%s/%s", dirname, name);
190         printf("path = %s ===================
", path);
191         struct stat st;
192         stat(path, &st);
193 
194         encode_str(enstr, sizeof(enstr), name);
195         // 如果是文件
196         if(S_ISREG(st.st_mode))
197         {
198             sprintf(buf+strlen(buf), 
199                     "<tr><td><a href="%s">%s</a></td><td>%ld</td></tr>",
200                     enstr, name, (long)st.st_size);
201         }
202         // 如果是目录
203         else if(S_ISDIR(st.st_mode))
204         {
205             sprintf(buf+strlen(buf), 
206                     "<tr><td><a href="%s/">%s/</a></td><td>%ld</td></tr>",
207                     enstr, name, (long)st.st_size);
208         }
209         send(cfd, buf, strlen(buf), 0);
210         memset(buf, 0, sizeof(buf));
211         // 字符串拼接
212     }
213 
214     sprintf(buf+strlen(buf), "</table></body></html>");
215     send(cfd, buf, strlen(buf), 0);
216 
217     printf("dir message send OK!!!!
");
218 #if 0
219     // 打开目录
220     DIR* dir = opendir(dirname);
221     if(dir == NULL)
222     {
223         perror("opendir error");
224         exit(1);
225     }
226 
227     // 读目录
228     struct dirent* ptr = NULL;
229     while( (ptr = readdir(dir)) != NULL )
230     {
231         char* name = ptr->d_name;
232     }
233     closedir(dir);
234 #endif
235 }
236 
237 // 发送响应头
238 void send_respond_head(int cfd, int no, const char* desp, const char* type, long len)
239 {
240     char buf[1024] = {0};
241     // 状态行
242     sprintf(buf, "http/1.1 %d %s
", no, desp);
243     send(cfd, buf, strlen(buf), 0);
244     // 消息报头
245     sprintf(buf, "Content-Type:%s
", type);
246     sprintf(buf+strlen(buf), "Content-Length:%ld
", len);
247     send(cfd, buf, strlen(buf), 0);
248     // 空行
249     send(cfd, "
", 2, 0);
250 }
251 
252 // 发送文件
253 void send_file(int cfd, const char* filename)
254 {
255     // 打开文件
256     int fd = open(filename, O_RDONLY);
257     if(fd == -1)
258     {
259         // show 404
260         return;
261     }
262 
263     // 循环读文件
264     char buf[4096] = {0};
265     int len = 0;
266     while( (len = read(fd, buf, sizeof(buf))) > 0 )
267     {
268         // 发送读出的数据
269         send(cfd, buf, len, 0);
270     }
271     if(len == -1)
272     {
273         perror("read file error");
274         exit(1);
275     }
276 
277     close(fd);
278 }
279 
280 // 解析http请求消息的每一行内容
281 int get_line(int sock, char *buf, int size)
282 {
283     int i = 0;
284     char c = '