黑马-web服务器(html与epoll)与http协议

黑马-web服务器

【回顾】两种网络通信模型:

B/S:Browser/Server

优点:1. 安全性好;2. 跨平台方便;3. 开发工作量小 (在线应用)

缺点:1. 不能缓存大量数据;2. 必须严格遵守http协议

C/S:Client/Server

优点:1. 可以缓存大量数据(需要下载应用);2. 可以自定义协议, 协议选择灵活(腾讯);3. 速度快

缺点:1. 安全性差;2. 开发工作量大;3. 跨平台难

我们访问的互联网网站,是通过域名,域名被解析为公网ip地址和端口,从而实现本机的浏览器和主机通信。

本文目标在本机实现一个简单的web服务器myhttpd。能够给本机浏览器提供服务,供用户借助浏览器访问主机中的文件

html(超文本标记语言-网页语言)

超文本即不仅限于页面上显示文字

本地写一个html,用浏览器直接点开,是一件很容易的事情。往html框架里面填和在线调试即可。

下面是一个404页面的html例子:

页面上也可以有其他元素:列表&图片和超链接

<!--html-demo2.html-->
<!DOCTYPE html>
<html>
	<head>
		<title>A Demo</title>
	</head>

	<body>
		<!--锚点-->
		<p id="top">

		<ul type="circle">
			<li>option1</li>
			<li>option2</li>
			<li>option3</li>
			<li>option4</li>
		</ul>

		<ol type="A">
			<li>option1</li>
			<li>option2</li>
			<li>option3</li>
			<li>option4</li>
		</ol>

		<img src="/home/daniel/图片/Vincent-Willem-Van-Gogh.jpg" alt="图片加载失败" title="VanGogh" width="300"/>
		<img src="/home/daniel/图片/Vincent-Willem-Van-Gogh.jpg" alt="图片加载失败" title="VanGogh" />
		<img src="/home/daniel/图片/Vincent-Willem-Van-Gogh.jpg" alt="图片加载失败" title="VanGogh" />
		<img src="/home/daniel/图片/Vincent-Willem-Van-Gogh.jpg" alt="图片加载失败" title="VanGogh" />
		<img src="/home/daniel/图片/Vincent-Willem-Van-Gogh.jpg" alt="图片加载失败" title="VanGogh" />

		<a href="http://jd.com" target="_blank" title="去京东">请跳转至京东</a>

		<!--给图片设置超链接-->
		<a href="http://jd.com" target="_blank" title="去京东">
			<img src="/home/daniel/图片/Vincent-Willem-Van-Gogh.jpg" alt="图片加载失败" title="VanGogh" width="100"/>
		</a>

		<a href="#top">回到顶部</a>

	</body>
</html>
这个是关键:现学现用网站

w3school 在线教程

菜鸟教程 - 学的不仅是技术,更是梦想!

XML、js、ajax、cgi、asp

js是脚本语言,让页面变活,使得用户和页面打交道

cgi建立了服务器和网页之间的通信;

浏览器和服务器的通信协议 http

思考 B/S 机制 或者说 浏览器机制:

当点击页面上的一个跳转链接/图片后,浏览器封装了客户的请求信息,把请求发送给对应服务器的端口,服务器收到请求做一个应答给浏览器,浏览器再把收到的数据解析出来。我们关注这个通信过程。

应用层协议--http协议格式

通常HTTP消息包括两种:客户机向服务器的请求 和 服务器向客户机的响应消息

请求消息Request(浏览器发给服务器):
http协议头
  1. 请求行:说明请求类型,要访问的资源以及使用的http版本
  2. 请求头:说明服务器要使用的附加信息
  3. 空行:必须有!即使没有请求数据。表示http协议头结束;如果是POST请求,传送数据在空行后面。【到这儿,http协议头结束。】
  4. 请求数据:也叫主体,可以添加任意的其他数据

当点击页面上一个超链接get请求时,浏览器就会自动组织封装一个协议

以下是浏览器发送给服务器的http协议头内容举例:

//第一行 GET 类请求;要访问的资源以及使用的http版本。对客户来说 /就是根目录,其他访问不到
GET /hello.c 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

//空行
\r\n
http请求类型 

响应消息(服务器发给浏览器):
http应答协议消息头
  1. 状态行:包括http协议版本号,状态码,状态信息
  2. 消息报头:说明客户端要使用的一些附加信息(有些行非必要,可以不回发)
  3. 空行:必须!【消息头】
  4. 响应正文:服务器返回给客户端的文本信息(或数据流)
//包括http协议版本号,状态码,状态信息
HTTP/1.1 200 OK

//消息报头:说明客户端要使用的一些附加信息
Server:xhttpd
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 //http默认,浏览器和服务器的通信模式一般都是,请求一次,应答一次,然后就断开。

//空行
\r\n

//响应正文
.....

关于状态行状态码/标号 常见解释: 

可以查一个http协议消息头吗?

另外看下http;协议格式

http协议学习网站

web服务器的 epoll-http-server 实现

  • 选择合适的模型(epoll、libevent)监听客户链接和处理读数据请求

//main.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "epoll_server.h"

int main(int argc, const char* argv[])
{
    if(argc < 3)
    {
        printf("eg: ./a.out port path\n");
        exit(1);
    }

    // 采用指定的端口
    int port = atoi(argv[1]);

    // 修改进程工作目录, 方便后续操作
    int ret = chdir(argv[2]);
    if(ret == -1)
    {
        perror("chdir error");
        exit(1);
    }
    
    // 启动epoll模型 
    epoll_run(port);

    return 0;
}
  • epoll_run(),模型起来之后分两条路,监听客户链接do_accept(lfd, epfd)
void epoll_run(int port)
{
    int i = 0;

    // 创建一个epoll树的根节点
    int epfd = epoll_create(MAXSIZE);
    if(epfd == -1) {   
        perror("epoll_create error");
        exit(1);
    }

    // 添加要监听的节点
    // 先添加监听lfd
    int lfd = init_listen_fd(port, epfd);

    // 委托内核检测添加到树上的节点
    struct epoll_event all[MAXSIZE];
    while(1) {
    
        int ret = epoll_wait(epfd, all, MAXSIZE, 0);
        if(ret == -1) {
        
            perror("epoll_wait error");
            exit(1);
        }

        // 遍历发生变化的节点
        for(i=0; i<ret; ++i)
        {
            // 只处理读事件, 其他事件默认不处理
            struct epoll_event *pev = &all[i];
            if(!(pev->events & EPOLLIN)) {
             
                // 不是读事件
                continue;
            }
            if(pev->data.fd == lfd){
             
                // 接受连接请求
                do_accept(lfd, epfd);
            } else {
            
                // 读数据
                printf("======================before do read, ret = %d\n", ret);
                do_read(pev->data.fd, epfd);
                printf("=========================================after do read\n");
            }
        }
    }
}

int init_listen_fd(int port, int epfd)
{
    // 创建监听的套接字
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    if(lfd == -1) {  
        perror("socket error");
        exit(1);
    }

    // lfd绑定本地IP和port
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(port);
    serv.sin_addr.s_addr = htonl(INADDR_ANY);

    // 端口复用
    int flag = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    
    int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
    if(ret == -1) {    
        perror("bind error");
        exit(1);
    }

    // 设置监听
    ret = listen(lfd, 64);
    if(ret == -1) {    
        perror("listen error");
        exit(1);
    }

    // lfd添加到epoll树上
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = lfd;
    ret = epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);
    if(ret == -1) {  
        perror("epoll_ctl add lfd error");
        exit(1);
    }
    return lfd;
}

// 接受新连接处理
void do_accept(int lfd, int epfd)
{
    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    int cfd = accept(lfd, (struct sockaddr*)&client, &len);
    if(cfd == -1) {  
        perror("accept error");
        exit(1);
    }

    // 打印客户端信息
    char ip[64] = {0};
    printf("New Client IP: %s, Port: %d, cfd = %d\n",
           inet_ntop(AF_INET, &client.sin_addr.s_addr, ip, sizeof(ip)),
           ntohs(client.sin_port), cfd);

    // 设置cfd为非阻塞
    int flag = fcntl(cfd, F_GETFL);
    flag |= O_NONBLOCK;
    fcntl(cfd, F_SETFL, flag);

    // 得到的新节点挂到epoll树上
    struct epoll_event ev;
    ev.data.fd = cfd;
    // 边沿非阻塞模式
    ev.events = EPOLLIN | EPOLLET;
    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev);
    if(ret == -1) { 
        perror("epoll_ctl add cfd error");
        exit(1);
    }
}

  • 和处理http读数据请求 do_read(pev->data.fd, epfd)。这是不同业务代码不同的地方。下面重点写do_read函数 【这里先写处理来读单文件的业务】
// 读数据
void do_read(int cfd, int epfd)
{
    // 将浏览器发过来的数据, 读到buf中 
    char line[1024] = {0};
    // 读请求行
    int len = get_line(cfd, line, sizeof(line));
    if(len == 0) {   
        printf("客户端断开了连接...\n");
        // 关闭套接字, cfd从epoll上del
        disconnect(cfd, epfd);         
    } else { 
    	printf("============= 请求头 ============\n");   
        printf("请求行数据: %s", line);
        // 还有数据没读完,继续读走。别放缓冲区,影响读后续新的数据
		while (1) {
			char buf[1024] = {0};
			len = get_line(cfd, buf, sizeof(buf));	
			if (buf[0] == '\n') {
				break;	
			} else if (len == -1)
				break;
		}
        printf("============= The End ============\n");
    }
    
    // 判断get请求
    if(strncasecmp("get", line, 3) == 0) { // 请求行: get /hello.c http/1.1   
        // 处理http请求
        http_request(line, cfd);
        
        // 关闭套接字, cfd从epoll上del
        disconnect(cfd, epfd);         
    }
}
  • 监听到读事件,按照需要,我们只需要 get_line()获取http协议的第一行,其他消息头内容不重要。操作句柄是cfd。(由于http协议的数据每一行的结尾是 /r/n,因此读一行要针对这个特点。)
// 可解析http请求消息的每一行内容,调用一次,读一行。
//读 行以/r/n结尾的http消息头 的第一行
int get_line(int sock, char *buf, int size)
{
    int i = 0;
    char c = '\0';
    int n;
    while ((i < size - 1) && (c != '\n')) {    
        n = recv(sock, &c, 1, 0);
        if (n > 0) {        
            if (c == '\r') {            
                n = recv(sock, &c, 1, MSG_PEEK);//MSG_PEEK模拟读一行,试探一下,下两个字符是不是/r/n,有可能只是/r,就不是结束符
                if ((n > 0) && (c == '\n')) {               
                    recv(sock, &c, 1, 0);
                } else {                            
                    c = '\n';
                }
            }
            buf[i] = c;
            i++;
        } else {       
            c = '\n';
        }
    }
    buf[i] = '\0';

    return i;
}
  • 从首行中拆分GET,文件名,协议版本。获取用户请求的文件名,判断文件是否存在并获取文件属性,用stat()函数。
// 断开连接的函数
void disconnect(int cfd, int epfd)
{
    int ret = epoll_ctl(epfd, EPOLL_CTL_DEL, cfd, NULL);
    if(ret == -1) {   
        perror("epoll_ctl del cfd error");
        exit(1);
    }
    close(cfd);
}

// http请求处理
void http_request(const char* request, int cfd)
{
    // 拆分http请求行
    char method[12], path[1024], protocol[12];
    //使用正则表达式的方法,从一行字符串中,拆分出三个字符串(行中他们以空格隔开)
    sscanf(request, "%[^ ] %[^ ] %[^ ]", method, path, protocol);
    printf("method = %s, path = %s, protocol = %s\n", method, path, protocol);

    // 转码 将不能识别的中文乱码 -> 中文
    // 解码 %23 %34 %5f
    decode_str(path, path);
        
    char* file = path+1; // 去掉path中的/ 获取访问文件名
    
    // 如果没有指定访问的资源, path就是“/”,因此下面返回数据就是默认显示资源目录中的内容(目录项)
    if(strcmp(path, "/") == 0) {    
        // file的值, 资源目录的当前位置
        file = "./";
    }

    // 获取文件属性
    struct stat st;
    int ret = stat(file, &st);
    if(ret == -1) { 
        send_error(cfd, 404, "Not Found", "NO such file or direntry");     
        return;
    }

    // 判断是目录还是文件
    if(S_ISDIR(st.st_mode)) {  		// 目录 
        // 发送头信息
        send_respond_head(cfd, 200, "OK", get_file_type(".html"), -1);
        // 发送目录信息
        send_dir(cfd, file);
    } else if(S_ISREG(st.st_mode)) { // 文件        
        // 发送消息报头
        send_respond_head(cfd, 200, "OK", get_file_type(file), st.st_size);
        // 发送文件内容
        send_file(cfd, file);
    }
}

正则表达式-脚本之家

  • 回发消息头字段中包括文件类型,定义个函数
// 通过文件名获取文件的类型
const char *get_file_type(const char *name)
{
    char* dot;

    // 自右向左查找‘.’字符, 如不存在返回NULL
    dot = strrchr(name, '.');   
    if (dot == NULL)
        return "text/plain; charset=utf-8";
    if (strcmp(dot, ".html") == 0 || strcmp(dot, ".htm") == 0)
        return "text/html; charset=utf-8";
    if (strcmp(dot, ".jpg") == 0 || strcmp(dot, ".jpeg") == 0)
        return "image/jpeg";
    if (strcmp(dot, ".gif") == 0)
        return "image/gif";
    if (strcmp(dot, ".png") == 0)
        return "image/png";
    if (strcmp(dot, ".css") == 0)
        return "text/css";
    if (strcmp(dot, ".au") == 0)
        return "audio/basic";
    if (strcmp( dot, ".wav" ) == 0)
        return "audio/wav";
    if (strcmp(dot, ".avi") == 0)
        return "video/x-msvideo";
    if (strcmp(dot, ".mov") == 0 || strcmp(dot, ".qt") == 0)
        return "video/quicktime";
    if (strcmp(dot, ".mpeg") == 0 || strcmp(dot, ".mpe") == 0)
        return "video/mpeg";
    if (strcmp(dot, ".vrml") == 0 || strcmp(dot, ".wrl") == 0)
        return "model/vrml";
    if (strcmp(dot, ".midi") == 0 || strcmp(dot, ".mid") == 0)
        return "audio/midi";
    if (strcmp(dot, ".mp3") == 0)
        return "audio/mpeg";
    if (strcmp(dot, ".ogg") == 0)
        return "application/ogg";
    if (strcmp(dot, ".pac") == 0)
        return "application/x-ns-proxy-autoconfig";

    return "text/plain; charset=utf-8";
}
  • 回发文件数据之前,先发应答消息头。
// 发送响应头
//消息头中有些参数是要外面传的,状态行的状态码 no,状态信息;消息报头的文件类型,长度等
void send_respond_head(int cfd, int no, const char* desp, const char* type, long len)
{
    char buf[1024] = {0};
    // 状态行
    sprintf(buf, "http/1.1 %d %s\r\n", no, desp);
    //send函数回发到服务器对应客户端的cfd
    send(cfd, buf, strlen(buf), 0);
    // 消息报头
    sprintf(buf, "Content-Type:%s\r\n", type);
    sprintf(buf+strlen(buf), "Content-Length:%ld\r\n", len);
    send(cfd, buf, strlen(buf), 0);
    // 空行
    send(cfd, "\r\n", 2, 0);
}
  • 如果文件存在:open()打开,read()内容,写回给浏览器

// 发送文件
void send_file(int cfd, const char* filename)
{
    // 打开文件
    int fd = open(filename, O_RDONLY);
    if(fd == -1) {   
        send_error(cfd, 404, "Not Found", "NO such file or direntry");
        exit(1);
    }

    // 循环读文件
    char buf[4096] = {0};
    int len = 0, ret = 0;
    while( (len = read(fd, buf, sizeof(buf))) > 0 ) {   
        // 发送读出的数据
        ret = send(cfd, buf, len, 0);
        if (ret == -1) {
            if (errno == EAGAIN) {
                perror("send error:");
                continue;
            } else if (errno == EINTR) {
                perror("send error:");
                continue;
            } else {
                perror("send error:");
                exit(1);
            }
        }
    }
    if(len == -1)  {  
        perror("read file error");
        exit(1);
    }

    close(fd);
}

至此,基本功能就写完了,可以基本测试一下。下面继续完善功能。

  • 考虑如果请求失败(文件不存在/发送失败等),服务器发送一个错误页面。即发送一个html类型的文本文件给浏览器。
void send_error(int cfd, int status, char *title, char *text)
{
	char buf[4096] = {0};

	sprintf(buf, "%s %d %s\r\n", "HTTP/1.1", status, title);
	sprintf(buf+strlen(buf), "Content-Type:%s\r\n", "text/html");
	sprintf(buf+strlen(buf), "Content-Length:%d\r\n", -1);
	sprintf(buf+strlen(buf), "Connection: close\r\n");
	send(cfd, buf, strlen(buf), 0);
	send(cfd, "\r\n", 2, 0);

	memset(buf, 0, sizeof(buf));

	sprintf(buf, "<html><head><title>%d %s</title></head>\n", status, title);
	sprintf(buf+strlen(buf), "<body bgcolor=\"#cc99cc\"><h2 align=\"center\">%d %s</h4>\n", status, title);
	sprintf(buf+strlen(buf), "%s\n", text);
	sprintf(buf+strlen(buf), "<hr>\n</body>\n</html>\n");
	send(cfd, buf, strlen(buf), 0);
	
	return ;
}

注意一点(浏览器知识):

  • 如果判断客户端请求的没有指定文件,就要把服务器提供的目录返回出来【简单看看】

本质上还是打开目录,读目录项,将目录项挨个写进html文件,再返回到浏览器,呈现出一个html页面。

// 发送目录内容
void send_dir(int cfd, const char* dirname)
{
    int i, ret;

    // 拼一个html页面<table></table>
    char buf[4094] = {0};

    sprintf(buf, "<html><head><title>目录名: %s</title></head>", dirname);
    sprintf(buf+strlen(buf), "<body><h1>当前目录: %s</h1><table>", dirname);

    char enstr[1024] = {0};
    char path[1024] = {0};
    
    // 目录项二级指针
    struct dirent** ptr;
    int num = scandir(dirname, &ptr, NULL, alphasort);
    
    // 遍历
    for(i = 0; i < num; ++i) {
    
        char* name = ptr[i]->d_name;

        // 拼接文件的完整路径
        sprintf(path, "%s/%s", dirname, name);
        printf("path = %s ===================\n", path);
        struct stat st;
        stat(path, &st);

		// 编码生成 %E5 %A7 之类的东西
        encode_str(enstr, sizeof(enstr), name);
        
        // 如果是文件
        if(S_ISREG(st.st_mode)) {       
            sprintf(buf+strlen(buf), 
                    "<tr><td><a href=\"%s\">%s</a></td><td>%ld</td></tr>",
                    enstr, name, (long)st.st_size);
        } else if(S_ISDIR(st.st_mode)) {		// 如果是目录       
            sprintf(buf+strlen(buf), 
                    "<tr><td><a href=\"%s/\">%s/</a></td><td>%ld</td></tr>",
                    enstr, name, (long)st.st_size);
        }
        ret = send(cfd, buf, strlen(buf), 0);
        if (ret == -1) {
            if (errno == EAGAIN) {
                perror("send error:");
                continue;
            } else if (errno == EINTR) {
                perror("send error:");
                continue;
            } else {
                perror("send error:");
                exit(1);
            }
        }
        memset(buf, 0, sizeof(buf));
        // 字符串拼接
    }

    sprintf(buf+strlen(buf), "</table></body></html>");
    send(cfd, buf, strlen(buf), 0);

    printf("dir message send OK!!!!\n");
  • 汉字字符编码和解码

        每一个汉字在浏览器URL栏中会被转码成Unicode码进行显示和往服务器传输。因此,在URL栏访问带有汉字的文件时,服务器要先进行解码操作,解码称为方块字,才能在在linux文件目录下找到对应的文件;相应的,应该在服务器回发数据给浏览器时进行编码操作(请求目录时候会用到)。

// 16进制数转化为10进制
int hexit(char c)
{
    if (c >= '0' && c <= '9')
        return c - '0';
    if (c >= 'a' && c <= 'f')
        return c - 'a' + 10;
    if (c >= 'A' && c <= 'F')
        return c - 'A' + 10;

    return 0;
}

/*
 *  这里的内容是处理%20之类的东西!是"解码"过程。
 *  %20 URL编码中的‘ ’(space)
 *  %21 '!' %22 '"' %23 '#' %24 '$'
 *  %25 '%' %26 '&' %27 ''' %28 '('......
 *  相关知识html中的‘ ’(space)是&nbsp
 */
void encode_str(char* to, int tosize, const char* from)
{
    int tolen;

    for (tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from) {    
        if (isalnum(*from) || strchr("/_.-~", *from) != (char*)0) {      
            *to = *from;
            ++to;
            ++tolen;
        } else {
            sprintf(to, "%%%02x", (int) *from & 0xff);
            to += 3;
            tolen += 3;
        }
    }
    *to = '\0';
}

void decode_str(char *to, char *from)
{
    for ( ; *from != '\0'; ++to, ++from  ) {     
        if (from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2])) {       
            *to = hexit(from[1])*16 + hexit(from[2]);
            from += 2;                      
        } else {
            *to = *from;
        }
    }
    *to = '\0';
}
调试遇到问题:

现象:在ubuntu的火狐浏览器 URL栏输入本地服务器的 ip:端口/文件名 之后,文本文件可以正常访问,但是图片和音频文件返回的是乱码。

定位:怀疑是返回数据没有指定对文件类型,代码中加打印,发现没问题。

解决:尝试修改火狐浏览器的 编码,没找到修改位置。改用谷歌浏览器,显示图片和播放音频正常。说明服务器代码没问题。

telnet调试

        也可使用telnet命令,借助IP和port,模拟浏览器行为(与命令行中的服务器通信),在终端中对访问的服务器进行调试,方便查看服务器会发给浏览器的http协议数据:

$ telnet 127.0.0.1 9527
GET /hello.c http/1.1

此时在终端中可查看到服务器回发给浏览器的http应答协议及数据内容,可根据该信息进行调试。

源码

epoll_server.c

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <ctype.h>
#include "epoll_server.h"

#define MAXSIZE 2000

void send_error(int cfd, int status, char *title, char *text)
{
	char buf[4096] = {0};

	sprintf(buf, "%s %d %s\r\n", "HTTP/1.1", status, title);
	sprintf(buf+strlen(buf), "Content-Type:%s\r\n", "text/html");
	sprintf(buf+strlen(buf), "Content-Length:%d\r\n", -1);
	sprintf(buf+strlen(buf), "Connection: close\r\n");
	send(cfd, buf, strlen(buf), 0);
	send(cfd, "\r\n", 2, 0);

	memset(buf, 0, sizeof(buf));

	sprintf(buf, "<html><head><title>%d %s</title></head>\n", status, title);
	sprintf(buf+strlen(buf), "<body bgcolor=\"#cc99cc\"><h2 align=\"center\">%d %s</h4>\n", status, title);
	sprintf(buf+strlen(buf), "%s\n", text);
	sprintf(buf+strlen(buf), "<hr>\n</body>\n</html>\n");
	send(cfd, buf, strlen(buf), 0);
	
	return ;
}

void epoll_run(int port)
{
    int i = 0;

    // 创建一个epoll树的根节点
    int epfd = epoll_create(MAXSIZE);
    if(epfd == -1) {   
        perror("epoll_create error");
        exit(1);
    }

    // 添加要监听的节点
    // 先添加监听lfd
    int lfd = init_listen_fd(port, epfd);

    // 委托内核检测添加到树上的节点
    struct epoll_event all[MAXSIZE];
    while(1) {
    
        int ret = epoll_wait(epfd, all, MAXSIZE, 0);
        if(ret == -1) {
        
            perror("epoll_wait error");
            exit(1);
        }

        // 遍历发生变化的节点
        for(i=0; i<ret; ++i)
        {
            // 只处理读事件, 其他事件默认不处理
            struct epoll_event *pev = &all[i];
            if(!(pev->events & EPOLLIN)) {
             
                // 不是读事件
                continue;
            }
            if(pev->data.fd == lfd){
             
                // 接受连接请求
                do_accept(lfd, epfd);
            } else {
            
                // 读数据
                printf("======================before do read, ret = %d\n", ret);
                do_read(pev->data.fd, epfd);
                printf("=========================================after do read\n");
            }
        }
    }
}

// 读数据
void do_read(int cfd, int epfd)
{
    // 将浏览器发过来的数据, 读到buf中 
    char line[1024] = {0};
    // 读请求行
    int len = get_line(cfd, line, sizeof(line));
    if(len == 0) {   
        printf("客户端断开了连接...\n");
        // 关闭套接字, cfd从epoll上del
        disconnect(cfd, epfd);         
    } else { 
    	printf("============= 请求头 ============\n");   
        printf("请求行数据: %s", line);
        // 还有数据没读完,继续读走
		while (1) {
			char buf[1024] = {0};
			len = get_line(cfd, buf, sizeof(buf));	
			if (buf[0] == '\n') {
				break;	
			} else if (len == -1)
				break;
		}
        printf("============= The End ============\n");
    }
    
    // 判断get请求
    if(strncasecmp("get", line, 3) == 0) { // 请求行: get /hello.c http/1.1   
        // 处理http请求
        http_request(line, cfd);
        
        // 关闭套接字, cfd从epoll上del
        disconnect(cfd, epfd);         
    }
}

// 断开连接的函数
void disconnect(int cfd, int epfd)
{
    int ret = epoll_ctl(epfd, EPOLL_CTL_DEL, cfd, NULL);
    if(ret == -1) {   
        perror("epoll_ctl del cfd error");
        exit(1);
    }
    close(cfd);
}

// http请求处理
void http_request(const char* request, int cfd)
{
    // 拆分http请求行
    char method[12], path[1024], protocol[12];
    sscanf(request, "%[^ ] %[^ ] %[^ ]", method, path, protocol);
    printf("method = %s, path = %s, protocol = %s\n", method, path, protocol);

    // 转码 将不能识别的中文乱码 -> 中文
    // 解码 %23 %34 %5f
    decode_str(path, path);
        
    char* file = path+1; // 去掉path中的/ 获取访问文件名
    
    // 如果没有指定访问的资源, 默认显示资源目录中的内容
    if(strcmp(path, "/") == 0) {    
        // file的值, 资源目录的当前位置
        file = "./";
    }

    // 获取文件属性
    struct stat st;
    int ret = stat(file, &st);
    if(ret == -1) { 
        send_error(cfd, 404, "Not Found", "NO such file or direntry");     
        return;
    }

    // 判断是目录还是文件
    if(S_ISDIR(st.st_mode)) {  		// 目录 
        // 发送头信息
        send_respond_head(cfd, 200, "OK", get_file_type(".html"), -1);
        // 发送目录信息
        send_dir(cfd, file);
    } else if(S_ISREG(st.st_mode)) { // 文件        
        // 发送消息报头
        send_respond_head(cfd, 200, "OK", get_file_type(file), st.st_size);
        // 发送文件内容
        send_file(cfd, file);
    }
}

// 发送目录内容
void send_dir(int cfd, const char* dirname)
{
    int i, ret;

    // 拼一个html页面<table></table>
    char buf[4094] = {0};

    sprintf(buf, "<html><head><title>目录名: %s</title></head>", dirname);
    sprintf(buf+strlen(buf), "<body><h1>当前目录: %s</h1><table>", dirname);

    char enstr[1024] = {0};
    char path[1024] = {0};
    
    // 目录项二级指针
    struct dirent** ptr;
    int num = scandir(dirname, &ptr, NULL, alphasort);
    
    // 遍历
    for(i = 0; i < num; ++i) {
    
        char* name = ptr[i]->d_name;

        // 拼接文件的完整路径
        sprintf(path, "%s/%s", dirname, name);
        printf("path = %s ===================\n", path);
        struct stat st;
        stat(path, &st);

		// 编码生成 %E5 %A7 之类的东西
        encode_str(enstr, sizeof(enstr), name);
        
        // 如果是文件
        if(S_ISREG(st.st_mode)) {       
            sprintf(buf+strlen(buf), 
                    "<tr><td><a href=\"%s\">%s</a></td><td>%ld</td></tr>",
                    enstr, name, (long)st.st_size);
        } else if(S_ISDIR(st.st_mode)) {		// 如果是目录       
            sprintf(buf+strlen(buf), 
                    "<tr><td><a href=\"%s/\">%s/</a></td><td>%ld</td></tr>",
                    enstr, name, (long)st.st_size);
        }
        ret = send(cfd, buf, strlen(buf), 0);
        if (ret == -1) {
            if (errno == EAGAIN) {
                perror("send error:");
                continue;
            } else if (errno == EINTR) {
                perror("send error:");
                continue;
            } else {
                perror("send error:");
                exit(1);
            }
        }
        memset(buf, 0, sizeof(buf));
        // 字符串拼接
    }

    sprintf(buf+strlen(buf), "</table></body></html>");
    send(cfd, buf, strlen(buf), 0);

    printf("dir message send OK!!!!\n");
#if 0
    // 打开目录
    DIR* dir = opendir(dirname);
    if(dir == NULL)
    {
        perror("opendir error");
        exit(1);
    }

    // 读目录
    struct dirent* ptr = NULL;
    while( (ptr = readdir(dir)) != NULL )
    {
        char* name = ptr->d_name;
    }
    closedir(dir);
#endif
}

// 发送响应头
void send_respond_head(int cfd, int no, const char* desp, const char* type, long len)
{
    char buf[1024] = {0};
    // 状态行
    sprintf(buf, "http/1.1 %d %s\r\n", no, desp);
    send(cfd, buf, strlen(buf), 0);
    // 消息报头
    sprintf(buf, "Content-Type:%s\r\n", type);
    sprintf(buf+strlen(buf), "Content-Length:%ld\r\n", len);
    send(cfd, buf, strlen(buf), 0);
    // 空行
    send(cfd, "\r\n", 2, 0);
}

// 发送文件
void send_file(int cfd, const char* filename)
{
    // 打开文件
    int fd = open(filename, O_RDONLY);
    if(fd == -1) {   
        send_error(cfd, 404, "Not Found", "NO such file or direntry");
        exit(1);
    }

    // 循环读文件
    char buf[4096] = {0};
    int len = 0, ret = 0;
    while( (len = read(fd, buf, sizeof(buf))) > 0 ) {   
        // 发送读出的数据
        ret = send(cfd, buf, len, 0);
        if (ret == -1) {
            if (errno == EAGAIN) {
                perror("send error:");
                continue;
            } else if (errno == EINTR) {
                perror("send error:");
                continue;
            } else {
                perror("send error:");
                exit(1);
            }
        }
    }
    if(len == -1)  {  
        perror("read file error");
        exit(1);
    }

    close(fd);
}

// 解析http请求消息的每一行内容
int get_line(int sock, char *buf, int size)
{
    int i = 0;
    char c = '\0';
    int n;
    while ((i < size - 1) && (c != '\n')) {    
        n = recv(sock, &c, 1, 0);
        if (n > 0) {        
            if (c == '\r') {            
                n = recv(sock, &c, 1, MSG_PEEK);
                if ((n > 0) && (c == '\n')) {               
                    recv(sock, &c, 1, 0);
                } else {                            
                    c = '\n';
                }
            }
            buf[i] = c;
            i++;
        } else {       
            c = '\n';
        }
    }
    buf[i] = '\0';

    return i;
}

// 接受新连接处理
void do_accept(int lfd, int epfd)
{
    struct sockaddr_in client;
    socklen_t len = sizeof(client);
    int cfd = accept(lfd, (struct sockaddr*)&client, &len);
    if(cfd == -1) {  
        perror("accept error");
        exit(1);
    }

    // 打印客户端信息
    char ip[64] = {0};
    printf("New Client IP: %s, Port: %d, cfd = %d\n",
           inet_ntop(AF_INET, &client.sin_addr.s_addr, ip, sizeof(ip)),
           ntohs(client.sin_port), cfd);

    // 设置cfd为非阻塞
    int flag = fcntl(cfd, F_GETFL);
    flag |= O_NONBLOCK;
    fcntl(cfd, F_SETFL, flag);

    // 得到的新节点挂到epoll树上
    struct epoll_event ev;
    ev.data.fd = cfd;
    // 边沿非阻塞模式
    ev.events = EPOLLIN | EPOLLET;
    int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev);
    if(ret == -1) { 
        perror("epoll_ctl add cfd error");
        exit(1);
    }
}

int init_listen_fd(int port, int epfd)
{
    // 创建监听的套接字
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    if(lfd == -1) {  
        perror("socket error");
        exit(1);
    }

    // lfd绑定本地IP和port
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(port);
    serv.sin_addr.s_addr = htonl(INADDR_ANY);

    // 端口复用
    int flag = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    
    int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
    if(ret == -1) {    
        perror("bind error");
        exit(1);
    }

    // 设置监听
    ret = listen(lfd, 64);
    if(ret == -1) {    
        perror("listen error");
        exit(1);
    }

    // lfd添加到epoll树上
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = lfd;
    ret = epoll_ctl(epfd, EPOLL_CTL_ADD, lfd, &ev);
    if(ret == -1) {  
        perror("epoll_ctl add lfd error");
        exit(1);
    }
    return lfd;
}

// 16进制数转化为10进制
int hexit(char c)
{
    if (c >= '0' && c <= '9')
        return c - '0';
    if (c >= 'a' && c <= 'f')
        return c - 'a' + 10;
    if (c >= 'A' && c <= 'F')
        return c - 'A' + 10;

    return 0;
}

/*
 *  这里的内容是处理%20之类的东西!是"解码"过程。
 *  %20 URL编码中的‘ ’(space)
 *  %21 '!' %22 '"' %23 '#' %24 '$'
 *  %25 '%' %26 '&' %27 ''' %28 '('......
 *  相关知识html中的‘ ’(space)是&nbsp
 */
void encode_str(char* to, int tosize, const char* from)
{
    int tolen;

    for (tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from) {    
        if (isalnum(*from) || strchr("/_.-~", *from) != (char*)0) {      
            *to = *from;
            ++to;
            ++tolen;
        } else {
            sprintf(to, "%%%02x", (int) *from & 0xff);
            to += 3;
            tolen += 3;
        }
    }
    *to = '\0';
}

void decode_str(char *to, char *from)
{
    for ( ; *from != '\0'; ++to, ++from  ) {     
        if (from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2])) {       
            *to = hexit(from[1])*16 + hexit(from[2]);
            from += 2;                      
        } else {
            *to = *from;
        }
    }
    *to = '\0';
}

// 通过文件名获取文件的类型
const char *get_file_type(const char *name)
{
    char* dot;

    // 自右向左查找‘.’字符, 如不存在返回NULL
    dot = strrchr(name, '.');   
    if (dot == NULL)
        return "text/plain; charset=utf-8";
    if (strcmp(dot, ".html") == 0 || strcmp(dot, ".htm") == 0)
        return "text/html; charset=utf-8";
    if (strcmp(dot, ".jpg") == 0 || strcmp(dot, ".jpeg") == 0)
        return "image/jpeg";
    if (strcmp(dot, ".gif") == 0)
        return "image/gif";
    if (strcmp(dot, ".png") == 0)
        return "image/png";
    if (strcmp(dot, ".css") == 0)
        return "text/css";
    if (strcmp(dot, ".au") == 0)
        return "audio/basic";
    if (strcmp( dot, ".wav" ) == 0)
        return "audio/wav";
    if (strcmp(dot, ".avi") == 0)
        return "video/x-msvideo";
    if (strcmp(dot, ".mov") == 0 || strcmp(dot, ".qt") == 0)
        return "video/quicktime";
    if (strcmp(dot, ".mpeg") == 0 || strcmp(dot, ".mpe") == 0)
        return "video/mpeg";
    if (strcmp(dot, ".vrml") == 0 || strcmp(dot, ".wrl") == 0)
        return "model/vrml";
    if (strcmp(dot, ".midi") == 0 || strcmp(dot, ".mid") == 0)
        return "audio/midi";
    if (strcmp(dot, ".mp3") == 0)
        return "audio/mpeg";
    if (strcmp(dot, ".ogg") == 0)
        return "application/ogg";
    if (strcmp(dot, ".pac") == 0)
        return "application/x-ns-proxy-autoconfig";

    return "text/plain; charset=utf-8";
}

epoll_server.h

#ifndef _EPOLL_SERVER_H
#define _EPOLL_SERVER_H

int init_listen_fd(int port, int epfd);
void epoll_run(int port);
void do_accept(int lfd, int epfd);
void do_read(int cfd, int epfd);
int get_line(int sock, char *buf, int size);
void disconnect(int cfd, int epfd);
void http_request(const char* request, int cfd);
void send_respond_head(int cfd, int no, const char* desp, const char* type, long len);
void send_file(int cfd, const char* filename);
void send_dir(int cfd, const char* dirname);
void encode_str(char* to, int tosize, const char* from);
void decode_str(char *to, char *from);
const char *get_file_type(const char *name);

#endif

main.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "epoll_server.h"

int main(int argc, const char* argv[])
{
    if(argc < 3)
    {
        printf("eg: ./a.out port path\n");
        exit(1);
    }

    // 采用指定的端口
    int port = atoi(argv[1]);

    // 修改进程工作目录, 方便后续操作
    int ret = chdir(argv[2]);
    if(ret == -1)
    {
        perror("chdir error");
        exit(1);
    }
    
    // 启动epoll模型 
    epoll_run(port);

    return 0;
}

makefile

src = $(wildcard ./*.c)  
obj = $(patsubst ./%.c, ./%.o, $(src)) 

myArgs= -Wall -g 
target=server
CC=gcc

ALL:$(target)

$(target):$(obj)
	$(CC) $^ -o $@ $(myArgs) 

$(obj):%.o:%.c
	$(CC) -c $^ -o $@ $(myArgs)

clean:
	-rm -rf $(obj) $(target)

.PHONY: clean ALL

回答一个经典问题:浏览器输入一个网址发生了什么? 

在浏览器地址栏输入url到按下回车发生了什么?-CSDN博客

在浏览器输入URL并回车后,会经历以下8个步骤:

  1. URL解析:浏览器会解析URL,将其分为协议、主机、端口、路径和查询参数等部分。
  2. DNS域名解析:浏览器会向DNS服务器发送请求,获取主机对应的IP地址。
  3. 建立TCP连接(三次握手):浏览器会向服务器发送SYN包,服务器回复ACK包和SYN包,浏览器再回复ACK包,完成三次握手。
  4. 发送HTTP请求:浏览器向服务器发送HTTP请求,请求中包含请求行、请求头、空行和请求数据等部分。
  5. 服务器处理相关的请求:服务器接收到请求后,会根据请求的内容进行处理,如请求一个页面,查询数据库、读取文件等。
  6. 返回响应的结果:服务器将处理后的结果封装成HTTP响应报文返回给浏览器,响应中包含状态行、响应头、空行和响应数据等部分。
  7. 关闭TCP连接(四次挥手):浏览器向服务器发送FIN包,服务器回复ACK包,服务器向浏览器发送FIN包,浏览器回复ACK包,完成四次挥手。
  8. HTML解析和页面渲染:浏览器接收到响应后,会对HTML进行解析,并根据CSS样式对页面进行渲染,最终呈现给用户。

目前系统 QT端 和 Web端 的区别

QT界面

优点:

运行稳定,可靠。有C++语法支持,开发友好。

界面实际开发只需要一个人即可完成。

目前本机QT端,直接从共享内存取出数据,不需要编码推流

系统运行更加高效。

支持更多的动画效果。

缺点:

依赖客户端,需要安装程序。

远程只能通过远程桌面的方式,且同一个时间段只能一个用户操作。

Web界面

优点:

不需要安装客户端。

在浏览器上就可以访问系统。

缺点:

需要谷歌浏览器,连接外网。

开发不支持C++,开发难度大。

Web开发周期长,框架熟悉时间长。

Web需要前段和后端,至少需要两个人同时开发,任务量比较大。

需要从共享内存取出数据,编码,推流。受网络环境影响大,CPU编码对CPU的资源的消耗也大。

从编码推流,web后端,web前端。涉及的环节较多,每个环节均会影响到了web显示。目前大家写的各个模块都没有经过长时间的测试,容易出bug的地方很多。

目前web大系统的耦合度高,安全机制不健全,容易被攻击。

目前系统 QT端 和 Web端 的区别 - 简书QT界面 优点: 运行稳定,可靠。有C++语法支持,开发友好。 界面实际开发只需要一个人即可完成。 目前本机QT端,直接从共享内存取出数据,不需要编码推流。 系统运行更加高效...icon-default.png?t=N7T8https://www.jianshu.com/p/7ae394e467b3

路由器的管理页面192.168.1.1

如何在计算机管理路由器,怎么查看路由器的管理IP地址?-CSDN博客

    想起来,路由器里面应该有一个web服务器,用户通过手机或者电脑连接自己新安装的路由器,输入默认的ip地址,192.168.1.1或者192.168.0.1(也是路由器内网地址),进入路由器的管理页面。

        开发时候,通过网线或者串口线,登录路由器页面;或者使用ipop工具,使用服务器远程登录协议 telnet或者ssh协议,登录到路由器的后台,进行路由器的升级,命令查询等操作。

        但是虽然能ping通,也要保证服务器的端口(telnet-23;ssh-22)是使能的。

学习参考: 

01-错误原因说明_哔哩哔哩_bilibili

【精选】Linux网络编程学习笔记_bufferevent缺点_Daniel_187的博客-CSDN博客

待看 

7.01 常见的Web技术_哔哩哔哩_bilibili

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值