利用libevent库实现一个简易的web服务器
在浏览器中我们可以通过IP地址+端口号访问服务器,
- 可以访问服务端中的各种图片、视频、音乐等文件
- 浏览器访问到不存在页面时会收到404错误页面提示
- 可以访问服务端中的目录文件
当使用makefile编译链接完成之后,即可得到server可执行文件
在终端下输入命令 ./server “自己定义一个端口号” “自己设定的根目录” 即可启动服务器
在浏览器中当我们输入 127.0.0.1:“自己设置的端口号” 即可访问服务器
- libevent_http.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>
#include <time.h>
#include <signal.h>
#include <ctype.h>
#include <errno.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include "libevent_http.h"
#define _HTTP_CLOSE_ "Connection: close\r\n"
int response_http(struct bufferevent *bev, const char *method, char *path)
{
if(strcasecmp("GET", method) == 0){
//get method ...
strdecode(path, path);
char *pf = &path[1];
if(strcmp(path, "/") == 0 || strcmp(path, "/.") == 0)
{
pf="./";
}
printf("***** http Request Resource Path = %s, pf = %s\n", path, pf);
struct stat sb;
if(stat(pf,&sb) < 0)
{
perror("open file err:");
send_error(bev);
return -1;
}
if(S_ISDIR(sb.st_mode))//处理目录
{
//应该显示目录列表
send_header(bev, 200, "OK", get_file_type(".html"), -1);
send_dir(bev, pf);
}
else //处理文件
{
send_header(bev, 200, "OK", get_file_type(pf), sb.st_size);
send_file_to_http(pf, bev);
}
}
return 0;
}
/*
*charset=iso-8859-1 西欧的编码,说明网站采用的编码是英文;
*charset=gb2312 说明网站采用的编码是简体中文;
*charset=utf-8 代表世界通用的语言编码;
* 可以用到中文、韩文、日文等世界上所有语言编码上
*charset=euc-kr 说明网站采用的编码是韩文;
*charset=big5 说明网站采用的编码是繁体中文;
*
*以下是依据传递进来的文件名,使用后缀判断是何种文件类型
*将对应的文件类型按照http定义的关键字发送回去
*/
const char *get_file_type(char *name)
{
char* dot;
dot = strrchr(name, '.'); //自右向左查找‘.’字符;如不存在返回NULL
if (dot == (char*)0)
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";