1. 实现思路
(1)编写函数解析http请求
GET /hello.html HTTP/1.1\r\n
将上述字符串分为三部分解析出来
(2)编写函数根据文件后缀,返回对应的文件类型
(3)sscanf - 读取格式化的字符串中的数据
使用正则表达式拆分
[^ ]的用法
(4)通过浏览器请求目录数据
(5)http中数据特殊字符编码解码问题
编码
解码
#include
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
数据转码
url在数据传输过程中不支持中文,需要转码。
- 汉字
- 特殊字符
查看manpage
man ascii
要处理可见字符
从space开始 - 32
前0-31个不可见
不需要转换的特殊字符
.
_
*
/
~
0-9
a-z
A-Z
需要转换的字符使用其16进制的值前加%表示
可以在shell下通过unicode工具查看
安装unicode
- sudo apt-get install unicode
正则表达式
参见:https://www.jb51.net/tools/regexsc.htm
实现的是从浏览器输入比如:127.0.0.1:8000/home,服务端会将/home目录下的文件及文件夹返回到浏览器。
1.头文件 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
epoll_server.h
2.mian函数 main.c
#include
#include
#include
#include "epoll_server.h"
int main(int argc, const char* argv[])//argv[0]为程序的名字
{
if(argc < 3)
{
printf("eg: ./a.out port path\n");
exit(1);
}
// 端口
int port = atoi(argv[1]);//端口在这里
// 修改进程的工作目录, 方便后续操作
int ret = chdir(argv[2]); //相当于cd,改为argv【2】
if(ret == -1)
{
perror("chdir error");
exit(1);
}
// 启动epoll模型
epoll_run(port);
return 0;
}
3.函数实现 epoll_server.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "epoll_server.h"
#define MAXSIZE 2000
void epoll_run(int port)
{
// 创建一个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, -1);//-1阻塞,直到IO事件发生了改变,并返回改变的个数。
if(ret == -1)
{
perror("epoll_wait error");
exit(1);
}
// 遍历发生变化的节点
for(int i=0; ievents & EPOLLIN))
{
// 不是读事件,写或异常
continue;
}
if(pev->data.fd == lfd)
{
// 接受连接请求
do_accept(lfd, epfd);
}
else
{
// 读数据,浏览器发过来的数据
do_read(pev->data.fd, epfd);
}
}
}
}
// 读数据
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("请求行数据: %s", line);
printf("============= 请求头 ============\n");
// 还有数据没读完
// 继续读
while(len)
{
char buf[1024] = {0};
len = get_line(cfd, buf, sizeof(buf));
printf("-----: %s", buf);
}
printf("============= The End ============\n");
}
// 请求行: get /xxx http/1.1
// 判断是不是get请求
if(strncasecmp("get", line, 3) == 0)
{
// 处理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请求行
// get /xxx http/1.1
char method[12], path[1024], protocol[12];//me存 get/post方法,path存资源目录
sscanf(request, "%[^ ] %[^ ] %[^ ]", method, path, protocol);//从requ到me,pa,pr,遇到空格结束。
printf("method = %s, path = %s, protocol = %s\n", method, path, protocol);
// 转码 将不能识别的中文乱码 - > 中文
// 解码 %23 %34 %5f
decode_str(path, path);
// 处理path /xx
// 去掉path中的/ , /没有用
char* file = path+1;
// 如果没有指定访问的资源, 默认显示资源目录中的内容
if(strcmp(path, "/") == 0)
{
// file的值, 资源目录的当前位置
file = "./";//没有资源
}
// 获取文件属性
struct stat st;
int ret = stat(file, &st);//用结构体
if(ret == -1)
{
// show 404
send_respond_head(cfd, 404, "File Not Found", ".html", -1);
send_file(cfd, "404.html");
}
// 判断是目录还是文件
// 如果是目录
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)
{
// 拼一个html页面
char buf[4094] = {0};
sprintf(buf, "目录名: %s ", dirname);
sprintf(buf+strlen(buf), "当前目录: %s
", dirname);
char enstr[1024] = {0};//路径
char path[1024] = {0};
// 目录项二级指针
struct dirent** ptr;
int num = scandir(dirname, &ptr, NULL, alphasort);// alphasort按字母排序,num为复制到ptr文件的数量
// 遍历
for(int i=0; id_name;//文件名
// 拼接文件的完整路径
sprintf(path, "%s/%s", dirname, name);
printf("path = %s ===================\n", path);//打印到页面
struct stat st;
stat(path, &st);// 获取文件属性
encode_str(enstr, sizeof(enstr), name);//中文乱马
// 如果是文件
if(S_ISREG(st.st_mode))
{
sprintf(buf+strlen(buf),
"%s %ld ",
enstr, name, (long)st.st_size);//href:去往的路径,页面跳转必写
}
// 如果是目录
else if(S_ISDIR(st.st_mode))
{
sprintf(buf+strlen(buf),
"%s/ %ld ",
enstr, name, (long)st.st_size);
}
send(cfd, buf, strlen(buf), 0);//发送到浏览器
memset(buf, 0, sizeof(buf));//清空
// 字符串拼接
}
sprintf(buf+strlen(buf), "
");
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);//输出到buf里 sprintf()
send(cfd, buf, strlen(buf), 0);//send 第四个参数一般设置为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)
{
// 打开文件,返回该文件的文件fd
int fd = open(filename, O_RDONLY);
if(fd == -1)
{
// show 404
return;
}
// 循环读文件
char buf[4096] = {0};
int len = 0;
while( (len = read(fd, buf, sizeof(buf))) > 0 )//len长度
{
// 发送读出的数据
send(cfd, buf, len, 0);
}
if(len == -1)
{
perror("read file error");
exit(1);
}
close(fd);
}
// 解析http请求消息的每一行内容
int get_line(int sock, char *buf, int size)//sock 为cfd
{
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);//peek,在缓存区 试探拷贝的作用,把从cfd接受的值 ,存到buf,改变c值
if ((n > 0) && (c == '\n'))
{
recv(sock, &c, 1, 0);//把/n 读出 ,正常情况
}
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,lfd: %d\n",
inet_ntop(AF_INET, &client.sin_addr.s_addr, ip, sizeof(ip)),
ntohs(client.sin_port), cfd,lfd);//inet_ntop网络字节序转本地ip,
// 设置cfd为非阻塞
int flag = fcntl(cfd, F_GETFL);//根据第二个参数,写第三个参数,F_GETFL获得文件状态
flag |= O_NONBLOCK;
fcntl(cfd, F_SETFL, flag);//设置文件状态为flag
// 得到的新节点挂到epoll树上
struct epoll_event ev;
ev.data.fd = cfd;//绑定cfd
// 边沿非阻塞模式 ,效率最高
ev.events = EPOLLIN | EPOLLET;
int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &ev);//使用结构体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);//ipv4,流模式,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;// 本机的ip 类型ipv4
serv.sin_port = htons(port);//输入的端口
serv.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY泛指本机所有ip 本机的ip 127.0.0.1
//lfd 端口复用,SO_REUSEADDR ,flag为1时 打开复用,为0关闭。
int flag = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));//用结构体,lfd和本地ip和端口绑定
if(ret == -1)
{
perror("bind error");
exit(1);
}
// 设置监听
ret = listen(lfd, 64);//同时最大64
if(ret == -1)
{
perror("listen error");
exit(1);
}
// lfd添加到epoll树上
struct epoll_event ev;//创建结构体
ev.events = EPOLLIN;//读
ev.data.fd = lfd;//结构体 绑定监听的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)是 
*/
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)
{//strchr :第一次出现字符*from的位置,isalnum 判断字符是否为数字或字母
*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 )
{//isxdigit 是否是16进制数
if (from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2]))
{
// 16进制数转化为10进制hexit,不区分大小写
*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";
}
程序里面函数层层嵌套,想搞明白的读者最好画一个程序结构图,以加深理解。
实现效果:能把本地目录映射到浏览器上,并实现查看,下载,超链接等功能。
补充:
(1)recv的flag
n = recv(sock, &c, 1, MSG_PEEK); - flag == MSG_PEEK - recv从缓冲区总读数据 - 拷贝的方式 1234567890 recv(fd, buf, size, 0); - 没数据了 recv(fd, buf, size, MSG_PEEK); - 有, 1234567890
(2)sscanf 函数
函数描述: 读取格式化的字符串中的数据。 函数原型: int sscanf( const char *buffer, const char *format, [ argument ] ... ); 1. 取到指定字符为止的字符串。如在下例中,取遇到空格为止字符串。 sscanf("123456 abcdedf", "%[^ ]", buf); printf("%s\n", buf); 结果为:123456 2. 取仅包含指定字符集的字符串。如在下例中,取仅包含1到9和小写字母的字符串。 sscanf("123456abcdedfBCDEF", "%[1-9a-z]", buf); printf("%s\n", buf); 结果为:123456abcdedf 3. 取到指定字符集为止的字符串。如在下例中,取遇到大写字母为止的字符串。 sscanf("123456abcdedfBCDEF", "%[^A-Z]", buf); printf("%s\n", buf); 结果为:123456abcdedf
参考 :https://www.cnblogs.com/xuejiale/p/10917407.html